[英]How do I create a class to sort a file in java
我让程序从用户读取文件(包含名字和姓氏)并打印出来。 现在,我需要编写一个方法来按姓氏对文件内容进行排序,以在主目录中调用。 我的问题是从哪里开始。 我开始为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)
{
}
}
创建一个实现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);
}
}
该类重写compareTo
方法,定义排序。
然后,您可以将读取的文件内容存储在TreeSet
类的SortedSet<Person>
。
假设i
是名字, j
是姓氏,请在代码中添加以下两行:
String check = "y";
SortedSet<Person> persons = new TreeSet<>();
和
System.out.println(i + " " + j + " ");
persons.add(new Person(i, j));
persons
将始终包含您到目前为止阅读的文件内容,并按姓氏排序。
}while(check.equals("y"));
然后,您可以执行以下操作:
for (Person person : persons) {
System.out.println(person);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.