0

I have my program reading in the file(which contain first name and last names) from the user and printing it out. Now I need to write a method to sort the contents of the file by last name to call in the main. My question is where to begin. I started making my class for sortFile but am stuck on where to even begin.

package javaproject1;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class JavaProject1 {

    public static void main(String[] args) throws FileNotFoundException 
    {
    String check = "y";
        do{
        Scanner fileRead = new Scanner(System.in);
        System.out.println("Enter the name of the file: ");
        File myFile = new File(fileRead.next());
        Scanner scanTwo = new Scanner(myFile);

        while(scanTwo.hasNext())
        {
            String i = scanTwo.next();
            String j = scanTwo.next();
            String sortLast;

            System.out.println(i + " " + j + " ");
        }

        System.out.println();
        Scanner anw = new Scanner(System.in);
        System.out.println("Add another? y/n ");
        check = anw.next();
        }while(check.equals("y"));
    }  

    public File sortFile(String sortLast)
    {

    }
}

1 Answer 1

3

Create a class Person implementing the Comparable interface:

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

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

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

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

The class overrides the compareTo method, defining the sorting.

You can then store the file contents you read, in a SortedSet<Person> like TreeSet.

Assuming i is the first name and j is the last name, add the following two lines to your code:

String check = "y";
SortedSet<Person> persons = new TreeSet<>();

and

System.out.println(i + " " + j + " ");
persons.add(new Person(i, j));

persons will always contain the file contents you read so far, sorted by last name.

After the }while(check.equals("y")); you can then do a:

for (Person person : persons) {
    System.out.println(person);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Looks as if you are working on the same project :-) -- Just found this stackoverflow.com/a/28530497/1990592 which is more elegant just using an ArrayList and the Comparator.comparing method. But it requires Java 8 as far as I know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.