Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Q2. Write a Java program that will sort first, middle and last names of the user

ID: 3587396 • Letter: Q

Question

Q2. Write a Java program that will sort first, middle and last names of the user. The program will ask user to enter the first, middle and the last names. It will also ask the sorting order e.g. you will enter 'l' for ascending order and ‘2' for descending order. The program should display the three names arranged in the specified sort order of their lengths. For example, if you enter name as: First name: Pradeep Middle name: K. Last name: Atrey Sort order: 1 As you can see the length of (or number of characters in) the first name is 7, middle name is 2 and last name is 5; and if you choose to ‘l, for ascending order, the output would be: K. Atrey Pradeep

Explanation / Answer

import java.io.*;
class sor
{
void dscsort(String s[], int n) //fucntion to sort in descending oder
{
for (int x=1 ;x<n; x++)
{
String t = s[x];

int y = x - 1;
while (y >= 0 && t.length() > s[y].length()) //checking for max length
{
s[y+1] = s[y];
y--;
}
s[y+1] = t;
}
}
void ascsort(String s[], int n) //function to sort in ascending order
{
for (int x=1 ;x<n; x++)
{
String t = s[x];

int y = x - 1;
while (y >= 0 && t.length() < s[y].length()) //checking for min length
{
s[y+1] = s[y];
y--;
}
s[y+1] = t;
}
}
  
void display(String str[], int n) //dipaly function
{
for (int i=0; i<n; i++)
System.out.print(str[i]+" ");
System.out.println();
}

public static void main()throws IOException //main function
{
int ch;
sor obj=new sor();
String fn,mn,ln;
String arr[] = new String[3];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("First Name: "); //accepitng the input from user
fn=br.readLine();
arr[0]=fn;
System.out.println("Middle Name: ");
mn=br.readLine();
arr[1]=mn;
System.out.println("Last Name: ");
ln=br.readLine();
arr[2]=ln;
int n = arr.length;
System.out.println("1.Ascending Order"); //choice of sort
System.out.println("2.Descending Order");
System.out.println("Sort Order: ");
ch=Integer.parseInt(br.readLine()); //taking user chouce
switch(ch)
{
case 1:
obj.ascsort(arr, n);
obj.display(arr, n);
break;
case 2:
obj.dscsort(arr, n);
obj.display(arr, n);
break;
default:
System.out.println("Invalid Choice");
break;
}
}
}