我想使用我在構造函數中提供的驗證檢查來初始化類Animal的實例字段。它似乎工作,如果我輸入正確的值 - 例如老虎 - 當調用構造函數,但不起作用,如果我輸入一個不正確的值後輸入相同的值。出於某種原因,它似乎不會退出while循環。我正在使用組合來測試字段值是否正確輸入。使用while循環不工作的構造函數輸入驗證
public class Animal {0}私有字符串類型;
public Animal(String type) {
enter code here
if ((type.equals("cheetah")) || (type.equals("tiger")) || (type.equals("Snake")) || (type.equals("lion"))) {
this.type = type;
}
else {
Scanner animaltype = new Scanner(System.in);
System.out.println("This animal has either left the jungle or is not present in the jungle. Please enter another value.");
type = animaltype.next();
while ((!type.trim().equals("cheetah") || (!type.trim().equals("tiger")) || (!type.trim().equals("Snake")) || (!type.trim().equals("lion"))))
{
if (type.equals("kangaroo")) {
System.out.println("Kangaroos have left the jungle. Please enter another value");
type = animaltype.next();
}
else if ((!type.trim().equals("kangaroo")) || (!type.trim().equals("cheetah")) || (!type.trim().equals("tiger")) || (!type.trim().equals("Snake")) || (!type.trim().equals("lion"))) {
System.out.println("This animal is not present in the Jungle. Please enter another value");
type = animaltype.next();
}
}
this.type = type;
}
}
public String getType() {
return this.type;
}
}
public class main {
public static void main(String[] args) {
Scanner animaltype = new Scanner(System.in);
System.out.println("Store the type of animal that is in the jungle");
String rt = animaltype.next();
Animal animal = new Animal(rt);
Jungle jungle = new Jungle(animal);
System.out.println(jungle.getAnimal().getType());
}
}
public class Jungle {
private Animal animal;
public Jungle(Animal animal) {
this.animal = animal;
}
public Animal getAnimal() {
return animal;
}
}