[英]How can i remove duplicated integers using this “removeDuplicate(ArrayList<Integer> list)” method?
[英]I can't get my removeDuplicate method to work?
我的程序读取一个输入文件,该文件是一个txt file
,其中包含名和姓的重复项。 我不确定为什么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));
}
}
}
为了简化代码,而无需以编程方式删除任何重复项,可以使用HashSet
, LinkedHashSet
或TreeSet
代替ArrayList
。
基本上是:
Set<String> names = new HashSet<String>(); // unordered, doesn't keep duplicates
Set<String> names = new LinkedHashSet<String>(); // keeps insertion order, doesn't keep duplicates
Set<String> names = new TreeSet<String>(); // ordered by lexicographic order, doesn't keep duplicates
然后可以处置find
和removeDuplicates
。
请注意,在任何情况下,重复项都区分大小写-但这就是您的代码当前所做的。
每个人对使用Set
的评论都是正确的。 这是您应该使用的数据结构。 但是,您代码的问题出在您的find()
方法中。 您传入一个int i
并设置String s = names.get(i)
,然后执行嵌套的for循环,但不要更改您的字符串s。
尝试这个:
public static int find(ArrayList<String> names) {
for (i = 0; i < names.size(); i = i + 1) {
String s = names.get(i);
for (int j = i + 1; j < names.size(); j = j + 1) {
if (s.equals(names.get(j))) {
return j;
}
}
}
return -1;
}
请注意,您将s设置为等于for循环中的第ith个元素。 您不再需要方法中的参数I。 但是,这可能会更改您的代码。 如果您只是想尝试查找每次发生的事情,则需要这样做:
public ArrayList<Integer> find(String name, ArrayList<String> names) {
ArrayList<Integer> duplicateIndices = new ArrayList<Integer>();
for (int i = 0; i < names.size(); i++) {
if (names.get(i).equals(name)) {
duplicateIndices.add(new Integer(i));
}
}
return duplicatIndices;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.