如果我理解正确的话,你应该实现这个头
public static void removeDuplicate(ArrayList<Integer> list)
它的名字判断方法,我会说的方法应该从列表中删除重复的,而不是(因为你正在做它现在)输入期间的do-while-loop。
所以第一个删除循环中的检查(if(!list.contains(value)&& value !=0)
),只需将用户类型的每个数字添加到列表中。您可以拨打removeDuplicate(list);
方法。如果你愿意,你可以在你的循环中添加这个调用,并且它会在每次输入后执行,或者在输入关闭时执行一次。
现在实施方法:
public static void removeDuplicate(ArrayList<Integer> list) { // this is the header you need to use
这里的问题是,该方法知道列表中,但不是这是一个可能重复的元素。所以,你必须寻找它
for (int i = 0; i < list.size(); i++) { // iterate through every element in the list
Integer current = list.get(i); // for convenience, save the current list item in a variable
所以,你检查列表中的每个整数 - 一个接一个..但是如果你想知道,如果存在整数第二次,你要搜索的尾巴列表。这意味着你必须在i之后检查子列表。
List sublist = list.subList(i + 1, list.size()); // the sublist with all elements of the list from i+1 to the end
你的list.contains(value)
行是正确的,你也可以在这里使用它。只是现在你怎么称呼它的子表
if(sublist.contains(current)){ // checks if the number is in the sublist
sublist.remove(current); // removes the number from the sublist
}
然而,这只会删除第一个复制。另外,您也可以在等于current
整数列表中删除每个项目:
while (sublist.contains(current)) {
sublist.remove(current);
}
就是这样。你的方法完成了。
}
}
它完成是因为您实际上正在处理程序中的唯一列表。即使您从sublist
删除一个整数,它实际上是从sublist
和真正的名单(该sublist
只是一个参考,而不是其自身的实际列表)
编辑删除
为了您在这里方便使用这两种方法的完整代码。如果您将代码与您的代码进行比较,您会发现没有太大区别:
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
System.out.print("Enter integers (input ends with 0): ");
int value;
do {
value = input.nextInt();
if (value != 0) { // this changed: add every number except 0
list.add(value);
}
} while (value != 0);
input.close();
removeDuplicate(list); // here you make the call for the new method
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
}
// and this is the new method
public static void removeDuplicate(ArrayList<Integer> list) {
for (int i = 0; i < list.size(); i++) {
Integer current = list.get(i);
List sublist = list.subList(i + 1, list.size());
while (sublist.contains(current)) {
sublist.remove(current);
}
}
}
如何删除?对不起,这个问题有答案,不能删除;代之以标志着主持人的注意力。此消息显示。 – Young 2014-11-12 22:58:24
你也可以把它留在这里。这个问题绝对没有错。也许别人可能会从这个线索中获益。此外,您可以通过单击左侧的透明“挂钩”来接受其中一个答案。这样,其他读者有更容易找到答案,这有助于你最和其他人不会尝试作出回应,因为“事情已了结” – GameDroids 2014-11-12 23:04:44
哦〜我知道了,谢谢 – Young 2014-11-14 00:04:21