简体   繁体   English

我如何创建一个类来对Java中的文件进行排序

[英]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. 我开始为sortFile做我的课,但被困在什至开始的地方。

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

    }
}

Create a class Person implementing the Comparable interface: 创建一个实现Comparable接口的Person类:

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. 该类重写compareTo方法,定义排序。

You can then store the file contents you read, in a SortedSet<Person> like TreeSet . 然后,您可以将读取的文件内容存储在TreeSet类的SortedSet<Person>

Assuming i is the first name and j is the last name, add the following two lines to your code: 假设i是名字, j是姓氏,请在代码中添加以下两行:

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. persons将始终包含您到目前为止阅读的文件内容,并按姓氏排序。

After the }while(check.equals("y")); }while(check.equals("y")); you can then do a: 然后,您可以执行以下操作:

for (Person person : persons) {
    System.out.println(person);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM