我正在编写一个 Java 应用程序,该应用程序应读取输入文件,并在每行上记录,并且字段之间用逗号分隔。应用程序的输出应在 stdout 上,格式如下:
Age1
Sex1
name1
name2
Sex2
name3
name4
e.g
33
Female
Jayanta
Kanupriya
44
Female
Lajjo
Rajjo
Male
Raghav
Sitaram
等等....
我创建了一个 Person 类来保存数据,并使用 compareTo 接口实现了 Comparable 接口,该接口对年龄进行了主要排序,对性别进行了次要排序。我可以稍后在名称上添加第三级排序。
public class Person implements Comparable<Person>{
private String name;
private int age;
private String sex;
/**
* @param age, sex and name
*/
public Person(String name, int age, String sex) {
this.setName(name);
this.setAge(age);
this.setSex(sex);
}
//getters and setters
@Override
public int compareTo(Person person) {
return this.age < person.getAge()?-1:this.age > person.getAge()?1:sortOnGender(person);
}
public int sortOnGender(Person person) {
if (this.sex.compareToIgnoreCase(person.getSex()) < 0) {
return -1;
}
else if (this.sex.compareToIgnoreCase(person.getSex()) > 0) {
return 1;
}
else {
return 0;
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(String.valueOf(this.age)).append('-').append(this.sex).append('-').append(this.name);
return sb.toString();
}
}
接下来,在 main 方法的 App 类中,我创建了一个 ArrayList of Persons 并填充了数据并使用 Collections.sort()进行了排序。我打印了 ArrayList 及其排序的顺序。但是问题是如何获取所需格式的数据。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
public class App {
//An array of persons
private static List<Person> persons = new ArrayList<Person>();
public static void main(String[] args) {
File inputfile = new File(args[0]);
if(inputfile.exists()) {
String line;
BufferedReader br;
StringTokenizer st = null;
try {
br = new BufferedReader(new FileReader(inputfile));
// Read comma seperated file line by line
while((line = br.readLine()) != null) {
//Break the line using "," as field seperator
st = new StringTokenizer(line, ",");
// Number of columns in the line
int numcols = st.countTokens();
if(numcols > 0) {
String[] cols = new String[st.countTokens()];
// Till the time columns are there in the line
while(st.hasMoreTokens()) {
for(int i=0; i < numcols; i++) {
cols[i] = st.nextToken();
}
}
// If there are elements in the cols array
if(cols.length !=0) {
// Create a list of persons
persons.add(new Person(cols[0].trim(), Integer.parseInt(cols[1].toString().trim()), cols[2].trim()));
}
}
else {
// Print error and continue to next record (Takes care of blank lines)
System.err.println("Error: No columns found in line");
}
}
// Sort the Collection
Collections.sort(persons);
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
else {
System.out.println("Specify the location of the input file");
}
System.out.println(persons);
}
}
2 回答
获得排序列表后,您应该可以执行以下操作
我不确定我是否会关注您,但是您只需要编写一个可以根据需要显示的方法即可!
如果要在控制台中打印,可以尝试以下操作: