這是一個按ID排序文件的完整程序。不過,我想按等級對它進行分類。我修改了幾次,但似乎沒有工作。有人可以指示我在哪裏更改ID以評分。另外,你認爲這個代碼可以簡化嗎?還是有其他代碼比這個代碼更簡單。如何按等級對文件進行排序?
對不起,不好的縮進,這個源代碼也可以找到here。
student.txt文件:
4 A 87 A
5 B 99 A+
1 C 75 A
2 D 55 C
3 E 68 B
源:
import java.io.*;
import java.util.*;
class ShowData implements Comparable {
int id;
String name;
int marks;
String grade;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setMarks(int marks) {
this.marks = marks;
}
public int getMarks() {
return marks;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getGrade() {
return grade;
}
public int compareTo(Object Student) throws ClassCastException {
if (!(Student instanceof ShowData))
throw new ClassCastException("Error");
int ide = ((ShowData) Student).getId();
return this.id - ide;
}
}
public class SortFile {
SortFile() {
int j = 0;
ShowData data[] = new ShowData[5];
try {
FileInputStream fstream = new FileInputStream("C:/student.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
ArrayList list = new ArrayList();
while ((strLine = br.readLine()) != null) {
list.add(strLine);
}
Iterator itr;
for (itr = list.iterator(); itr.hasNext();) {
String str = itr.next().toString();
String[] splitSt = str.split(" ");
String id = "", name = "", marks = "", grade = "";
for (int i = 0; i < splitSt.length; i++) {
id = splitSt[0];
name = splitSt[1];
marks = splitSt[2];
grade = splitSt[3];
}
data[j] = new ShowData();
data[j].setId(Integer.parseInt(id));
data[j].setName(name);
data[j].setMarks(Integer.parseInt(marks));
data[j].setGrade(grade);
j++;
}
Arrays.sort(data);
File file = new File("C:/new.txt");
FileWriter fw = new FileWriter(file, true);
BufferedWriter out = new BufferedWriter(fw);
System.out.println("********Sorted by id********");
String strVal = "";
for (int i = 0; i < 5; i++) {
ShowData show = data[i];
int no = show.getId();
String name = show.getName();
int marks = show.getMarks();
String grade = show.getGrade();
System.out.println(no + " " + name + " " + marks + " " + grade);
String d = no + " " + name + " " + marks + " " + grade;
ArrayList al = new ArrayList();
al.add(d + "\n");
Iterator itr1 = al.iterator();
while (itr1.hasNext()) {
out.write(itr1.next().toString());
out.newLine();
}
}
out.close();
} catch (Exception e) {
}
}
public static void main(String[] args) {
SortFile data = new SortFile();
}
}
你試過了什麼?你有什麼麻煩? – SLaks 2013-03-03 17:39:36
我認爲從逐字複製網站代碼出現*嚴重問題,然後詢問該方法是否存在問題。從兩個步驟開始,從頭開始,以便您可以按需重現這種行爲:您需要什麼來讀取文件,需要關閉哪部分行以對字符串進行排序,以及使用哪些方法那會帶來什麼?我看到解決方案比這裏介紹的要容易一點。 – Makoto 2013-03-03 17:48:07
正如我上面提到的那樣,我將ID更改爲等級以按GRADE排序。我嘗試了多次修改代碼,但沒有實現任何功能。我不想發佈我修改的代碼,因爲它們包含很多錯誤。 – Ramal 2013-03-03 18:13:26