コンストラクタで提供した検証チェックを使用して、クラスAnimalのインスタンスフィールドを初期化しようとしています。コンストラクタを呼び出すときにtigerなどの正しい値を入力すると正しく機能しているようですが、誤った値を入力しても同じ値を入力しても機能しません。何らかの理由で、whileループを終了していないようです。フィールド値が正しく入力されたかどうかをテストするために合成を使用しています。whileループを使用しないコンストラクタの入力検証
public class Animal { プライベートString型。
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;
}
}