我的程序讀取輸入文件,這是一個txt file
,其中包含名字和姓氏的重複。我不確定爲什麼removeDuplicate
方法不刪除重複項,而是給我一個錯誤。我究竟做錯了什麼?我無法讓我的removeDuplicate方法工作?
public static void main(String[] args) throws IOException {
ArrayList<String> names = new ArrayList<String>();
String fName;
String lName;
System.out.println("What is the input file?");
Scanner kb = new Scanner(System.in);
String fileName = kb.next();
File list = new File(fileName);
Scanner in = new Scanner(list);
System.out.println("What is the output file?");
String outFileName = kb.next();
PrintWriter outFile = new PrintWriter(outFileName);
while (in.hasNext()) {
fName = in.next();
lName = in.next();
names.add(fName + " " + lName);
removeDuplicates(names);
display(names);
outFile.println(fName + " " + lName);
}
outFile.close();
}
}
這裏的方法我的公共主
public class StudentList {
public static void display(ArrayList<String> n) {
// step through all positions of the ArrayList n and display the values
// at each positoin
for (int i = 0; i < n.size(); i = i + 1) {
System.out.println(n.get(i));
}
}
public static int find(ArrayList<String> names, int i) {
String s = names.get(i);
for (i = 0; i < names.size(); i = i + 1) {
for (int j = i + 1; j < names.size(); j = j + 1) {
if (s.equals(names.get(j))) {
return j;
}
}
}
return -1;
}
public static void removeDuplicates(ArrayList<String> names) {
for (int i = 0; i < names.size(); i = i + 1) {
while (find(names, i) > 0) {
names.remove(find(names, i));
}
}
}
你得到什麼錯誤? –
爲什麼不使用'Set'而不是'List '?這種方式重複被自動刪除 –
每次添加新的名稱時,是否真的要打印出整個名稱列表?另外,如果您想使用此方法,則只需在添加完所有內容後刪除一次重複項。此刻,當只有一個可能的重複時,您會比較每對可能的對。 – Holloway