FrankyFigs
FrankyFigs

Reputation: 13

How do I create a class to sort a file in java

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)
    {

    }
}

Upvotes: 0

Views: 61

Answers (1)

user1990592
user1990592

Reputation:

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);
}

Upvotes: 3

Related Questions