2 回答

TA貢獻(xiàn)1864條經(jīng)驗 獲得超2個贊
事實上,你不需要額外的條件。
如果您編寫一個單獨的條件來檢查是否沒有寵物的名字與輸入匹配,那么您將迭代寵物列表兩次,這是多余的。
請注意,如果發(fā)現(xiàn)寵物,if內(nèi)部for將被運(yùn)行。我們可以boolean在 中將變量設(shè)置為 true if,并在循環(huán)后檢查它是否找到寵物:
// 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貢獻(xiàn)1856條經(jīng)驗 獲得超5個贊
您可以使用一個標(biāo)志“petFound”,如果找到了 pet,則在 for 循環(huán)中將其設(shè)置為 true。在循環(huán)后檢查標(biāo)志值,如果標(biāo)志為假,則打印未找到消息。
如果您正在研究 Java8,請?zhí)鎿Q循環(huán)
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
}
添加回答
舉報