黑马程序员技术交流社区
标题:
这个题目怎么做啊?急!
[打印本页]
作者:
孤影卓尔
时间:
2014-2-24 16:16
标题:
这个题目怎么做啊?急!
有一个txt文件 里面有两列 姓名和年龄 要求读取这个txt文件 按年龄排序 然后新生成一个txt把排序完成后的写在这个txt里 ... 这要怎样完成啊 求大神指点 最好有代码 谢谢了 详细点
作者:
长石
时间:
2014-2-24 16:34
1 先建一个student类 有姓名和年龄属性 还要实现comparable接口 compareTo方法按年龄比较
2 主方法建立字符读取流缓冲区 读取txt文件
按行读去 用split方法切割字符串 new出student对象 加入一个TreeSet集合
再将集合的元素写入另一个txt文件
作者:
丶小天
时间:
2014-2-24 16:40
你运行看看:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class $ {
private static List<Person> data = new ArrayList<Person>();
public static void main(String... _) throws Exception {
Scanner in = null;
try {
in = new Scanner(new File("D:/a.txt"));
while (in.hasNextLine()) {
String str = in.nextLine();
String[] arr = str.split(" ");// 注意txt里面两列之间需有个空格
data.add(new Person(arr[0], toInt(arr[1])));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}
System.out.println("pai xu qian:" + data);
Collections.sort(data, new Comparator<Person>() {
public int compare(Person o1, Person o2) {
// 按年龄升序
return o1.getAge() - o2.getAge();
// 按年龄降序
// return o2.getAge() - o1.getAge();
}
});
System.out.println("pai xu hou:" + data);
FileWriter fw = new FileWriter(new File("D:/b.txt"));
for (Person p : data) {
fw.write(p.getName() + " " + p.getAge() + "\r\n");
}
fw.flush();
fw.close();
System.out.println("已经保存到D:/b.txt");
}
private static int toInt(String str) {
try {
return Integer.parseInt(str);
} catch (Exception e) {
return 0;
}
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "{" + name + "," + age + "}";
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2