내 프로그램은 성과 이름의 중복을 포함하는 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();
}
}
여기에 코드를 단순화하고 프로그래밍 어떤 당신이 HashSet
, LinkedHashSet
또는 TreeSet
대신 ArrayList
의 사용할 수있는 중복 제거 할 필요는 없습니다하기 위해
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));
}
}
}
어떤 오류가 발생합니까? –
'List'대신'Set '을 사용하지 않는 이유는 무엇입니까? 이 방법은 중복 제거가 자동으로 수행됩니다 –
새 이름을 추가 할 때마다 전체 이름 목록을 실제로 인쇄 하시겠습니까? 또한이 방법을 사용하려면 모든 항목을 추가 한 후에 중복 항목을 한 번만 제거하면됩니다. 현재 가능한 복제본이 하나 뿐인 경우 가능한 모든 쌍을 비교하고 있습니다. – Holloway