java读取文件中的内容并进行排序。求大神支招 ~急!!
展开全部
public class SortFile {
public static void main(String[] args) {
new SortFile().doWork();
}
private static final String FILE = "data.txt"; // !!!modify
class Course implements Comparable<Course> {
String name;
String teacher;
int period;
int price;
Course(String name, String teacher, int period, int price) {
this.name = name;
this.teacher = teacher;
this.period = period;
this.price = price;
}
@Override
public int compareTo(Course target) {
if (price == target.price) {
return target.period - period;
}
return target.price - price;
}
@Override
public String toString() {
return "[NAME: " + name + " , TEACHER: " + teacher + " , PERIOD: " + period + " , PRICE: " + price + "]";
}
}
private void doWork() {
List<Course> courses = new ArrayList<Course>();
readFile(courses);
Collections.sort(courses);
int max = courses.size() >= 3 ? 3 : courses.size();
for (int i = 0; i < max; i++) {
System.out.println(courses.get(i).toString());
}
}
private void readFile(List<Course> courses) {
try {
BufferedReader br = new BufferedReader(new FileReader(FILE));
String line = null;
while ((line = br.readLine()) != null) {
String[] data = line.split(" ");
try {
data[3] = data[3].substring(0, data[3].length() - 1); // delete 元
Course course = new Course(data[0], data[1], Integer.parseInt(data[2]), Integer.parseInt(data[3]));
courses.add(course);
} catch (Exception e) {}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
更多追问追答
追问
为什么运行不了呢?
追答
出什么错。。。
private static final String FILE = "data.txt"; // !!!modify
这一行要改成你自己的文件的路径。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询