2 回答
TA贡献1864条经验 获得超2个赞
事实上,你不需要额外的条件。
如果您编写一个单独的条件来检查是否没有宠物的名字与输入匹配,那么您将迭代宠物列表两次,这是多余的。
请注意,如果发现宠物,if内部for将被运行。我们可以boolean在 中将变量设置为 true if,并在循环后检查它是否找到宠物:
// in the else branch of the outermost if
boolean petFound = false; // note this line
input = input.toLowerCase();
for(Pet pet: h1.getPets()){
String text1 = String.format("%s%10s%10s\n", "Namn:", "Mått:", "Sort:");
String text2 = String.format("%s%10.2f%16s", pet.getName(), pet.measureFood(), pet.getFoodName());
String text3 = "---------------------------------------\n";
text1 = text1 + text3 + text2;
if (pet.getName().toLowerCase().equals(input)) {
JOptionPane.showMessageDialog(null,text1);
petFound = true; // note this line
break;
}
}
if (!petFound) {
// show the message that there is no pet with the input name
}
TA贡献1856条经验 获得超5个赞
您可以使用一个标志“petFound”,如果找到了 pet,则在 for 循环中将其设置为 true。在循环后检查标志值,如果标志为假,则打印未找到消息。
如果您正在研究 Java8,请替换循环
Optional<Pet> pet = h1.getPets().stream().filter(pet.getName().toLowerCase().equals(input)).findFirst();
if(pet.isPresent()){
pet.get();// gives the pet
}
else{
// Print pet not found
}
添加回答
举报