Brandon Brandon - 2 months ago 14
Java Question

Java: Just sorting strings after the space?

I'm making a program that sorts names based on last name, but user enters a full name such as "John Smith" and I can't get it to sort by the name after the space.

It seems to only want to sort by the first name entered and ignore the last, but I want to sort by last name

System.out.println("Welcome to name sorter program");

//Set max names to 10
String [] names = new String[10];
String temp;
for (int i = 0; i < names.length; i++)
{
System.out.println("Enter person " +(i + 1));
//Name entered is assigned to each array slot
names[i] = userInput.nextLine();
}
for (int i = 0; i < names.length; i++)
{
for (int j = i + 1; j < names.length; j++ )
{
if (names[i].compareTo(names[j]) > 0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.println("Sorted Names Are...");
for (int i = 0; i < names.length - 1; i++)
{
System.out.println(names[i]);
}
System.out.println(names[names.length - 1]);
}

Answer

My answer is almost the same of @BahramdunAdil:

public class Main {

    public static void main(String[] args) {

        final int MAX = 10;

        Scanner userInput = new Scanner(System.in);

        List<Person> names = new ArrayList<Person>();

        System.out.println("Welcome to name sorter program!\n");

        for (int i = 0; i < MAX; i++) {
            System.out.println("Enter person " + (i + 1) + ":");
            names.add(new Person(userInput.nextLine()));
        }

        userInput.close();

        Collections.sort(names);

        System.out.println("\nSorted Names Are...");

        for (Person name : names)
            System.out.println(name);
    }

}

i.e, you can turn your code simpler creating a Person Class that implements Comparable:

public class Person implements Comparable<Person> {
    private String firstName;
    private String lastName;

    public Person(String name) {
        this.firstName = name.split(" ")[0];
        this.lastName = name.split(" ")[1];
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    @Override
    public int compareTo(Person o) {
        return lastName.compareTo(o.getLastName());
    }

    @Override
    public String toString() {
        return firstName + " " + lastName;
    }
}

Input:

Welcome to name sorter program!

Enter person 1:
Bill Gates
Enter person 2:
Amancio Ortega
Enter person 3:
Warren Buffett
Enter person 4:
Carlos Slim Helu
Enter person 5:
Jeff Bezos
Enter person 6:
Mark Zuckerberg
Enter person 7:
Larry Ellison
Enter person 8:
Michael Bloomberg
Enter person 9:
Charles Koch
Enter person 10:
David Koch

Output:

Sorted Names Are...
Jeff Bezos
Michael Bloomberg
Warren Buffett
Larry Ellison
Bill Gates
Charles Koch
David Koch
Amancio Ortega
Carlos Slim
Mark Zuckerberg