help with java please! write a program in java that does the folowing and write
ID: 671076 • Letter: H
Question
help with java please!
write a program in java that does the folowing and write comments within the program. i.e. //this does this
Objective: Write a program where the user enters 10 names. First name followed by the last name with a space in between. After the 10 names have been inputted the names are sorted by the last names. You do not have to worry about invalid inputs. Also do not worry about sorting more than the first letter in the last name, so for instance Savage and Shepherd are interchangeable as they both start with 'S HINT: The string methods indexOf and charAt are vital. Example Dialog: Welcome to name sorter program Enter person 1 JJ Shepherd Enter person 2 William Hoskins Enter person 3 Jake Roberts Enter person 4 Daniel Bryan Enter person 5 Randy Savage Enter person 6 Ric Flair Enter person 7 Kevin Nash Enter person 8 Scott Hall Enter person 9 Steve Austin Enter person 10 Dwayne JohnsonExplanation / Answer
import java.util.*;
class Name_Sort
{
public static void main (String args[])
{
int n;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of names you want to enter:");
n = s.nextInt();
String names[] = new String[n];
// Scanner s1 = new Scanner(System.in);
// System.out.println("Enter all the names:");
s.nextLine();
for(int i = 0; i < n; i++)
{
// enter first and last name
System.out.println("Enter person "+i+":");
names[i] = s.nextLine();
}
String temp1;
for (int b = 0; b<n; b++)
{
for (int j=b+1; j<n; j++)
{
if ((compareLastNames(names[b], names[j]))>0)
{
temp1 = names[b];
names[b] = names[j];
names[j] = temp1;
}
}
}
for(int i=0;i<n;i++)
{
System.out.println(names[i]);
}
}
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.