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
}
添加回答
舉報