我会喜欢一些帮助。这里的问题是当请求的狗碰巧索引为0时,循环工作正常并且只通过第一个if语句。如果请求的狗碰巧有另一个索引,那么两个if语句都被读取......任何可以看到解决方案的人? :)
protected void removeDog() {
String k = readString("Name of dog you want to delete from list: ");
boolean found = false;
for (int x = 0; x < dogRegister.size(); x++) {
if (dogRegister.get(x).getName().equalsIgnoreCase(k)) {
dogRegister.remove(x);
System.out.println(k + " has been deleted from list.");
found = true;
break;
}
else if (!found) {
System.out.println(k + " could not be found in list.");
}
}
}
答案 0 :(得分:1)
每次迭代if
循环时,您都会执行else if
或for
。如果它不是第一个,那么你将无法找到&#34;&#34;为每次迭代发送一次消息,直到找到并删除它或者您已经用完该列表。
无法找到&#34;&#34;只有在您根本找不到该消息时才打印消息,将else if
移到for
循环之外,删除其他内容:
for (int x = 0; x < dogRegister.size(); x++) {
if (dogRegister.get(x).getName().equalsIgnoreCase(k)) {
dogRegister.remove(x);
System.out.println(k + ” has been deleted from list.”);
found = true;
break;
}
}
if (!found) {
System.out.println(k + ” could not be found in list.");
}
答案 1 :(得分:0)
我会避免使用.get(i)
读取Java集合,即使它是ArrayList
。您可以使用迭代器,它们可以简化任务。
protected void removeDog() {
String dogName = readString("Name of dog you want to delete from list:");
boolean found = false;
// I assume there is a class "Dog"
for (Iterator<Dog> it = dogRegister.iterator(); it.hasNext(); ) {
Dog dog = it.next();
if (dog.getName().equalsIgnoreCase(dogName)) {
it.remove();
found = true;
break;
}
}
if (found) //print something...
else //print something else...
}
答案 2 :(得分:0)
protected void removeDog() {
String k = readString(”Name of dog you want to delete from list: ");
boolean found = false;
for (int x = dogRegister.size(); x > 0; x--) {
if (dogRegister.get(x).getName().equalsIgnoreCase(k)) {
dogRegister.remove(x);
System.out.println(k + ” has been deleted from list.”);
found = true;
break;
}
else if ( x == 0){
System.out.println(k + ” could not be found in list.");
}
}
}
如果到达列表的末尾,将会出现“在列表中找不到K”。之前发生的事情是,每次运行循环时,除非在第一个位置找到您的狗,否则它将始终显示NOT FOUND你的阵列。它将一直持续到最后找到或退出。