생성자에서 제공 한 유효성 검사를 사용하여 클래스 Animal의 인스턴스 필드를 초기화하려고합니다. 생성자를 호출 할 때 올바른 값 (예 : 호랑이)을 입력하면 잘못된 값을 입력 한 후에 동일한 값을 입력해도 작동하지 않는 것 같습니다. 어떤 이유로 그것은 while 루프를 종료하지 않는 것 같습니다. 필드 값이 올바르게 입력되었는지 테스트하기 위해 컴포지션을 사용하고 있습니다.while 루프가 작동하지 않는 생성자 입력 유효성 확인
공용 클래스 동물 { private String type;
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;
}
}