如果缺少信息,我提前道歉,这对我来说是新的!
所以作业说;有一家宠物酒店(狗、猫和蛇),该程序应该打印出他们应该吃多少食物以及什么类型的食物。用户写下宠物的名字,它应该打印出来。
我不明白的是如何编写一个条件语句,该条件语句表示如果没有元素的名称与输入匹配,则写“我们酒店没有具有该名称(输入)的宠物”。
我遇到这个问题的原因是因为我无法到达任何元素,除非我创建一个 foreach 循环,并且我不希望在循环结束后为每个元素弹出一条消息。
import javax.swing.*;
public class Main {
public static void main(String[] args) {
Dog d1 = null;
Dog d2 = null;
Cat c1 = null;
Cat c2 = null;
Snake s1 = null;
try {
d1 = new Dog("Sixten", 5);
d2 = new Dog("Dogge", 10);
c1 = new Cat("Venus", 5);
c2 = new Cat("Ove", 3);
s1 = new Snake("Hypno", 1);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
System.exit(0);
}
Hotel h1 = new Hotel();
h1.addPet(d1);
h1.addPet(d2);
h1.addPet(c1);
h1.addPet(c2);
h1.addPet(s1);
h1.getPets(); // gets the list with all the pets
while (true) {
String input = JOptionPane.showInputDialog("What pet(name of pet) needs feeding?");
if (input == null){
System.exit(0);
break;
}
else if(input.equals("")){
JOptionPane.showMessageDialog(null, "Invalid input!");
}// HERE IS WHERE I WANT THE STATEMENT
else if(**Statement that says if input isn't equal to any of the animal's name**){
}
else{
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);
break;
}
}
}
}
}
}
慕斯王
RISEBY
相关分类