2017-04-16 7 views
1

생성자에서 제공 한 유효성 검사를 사용하여 클래스 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; 
    } 
} 

답변

0

while 루프의 조건이 잘못되었습니다. type이 적어도 하나의 문자열과 같지 않으면 계속 진행합니다. 음, type은 둘 이상의 문자열과 같을 수 없으므로 while 루프는 영원히 계속됩니다. 이 현상은 or을 사용 중이며 연산자가 and 일 필요가 있기 때문에 발생합니다. 조건을 (!type.trim().equals("cheetah") && (!type.trim().equals("tiger")) && (!type.trim().equals("Snake")) && (!type.trim().equals("lion"))) 또는 대체적으로 !(type.trim().equals("cheetah) || type.trim().equals("tiger") || type.trim().equals("Snake") || type.trim().equals("lion"))으로 바꿔야합니다. 두 사람 모두 type이 문자열 중 하나와 같으면 while 루프에서 빠져 나온다고 말합니다.

PS : Scannernext 방법은 기본적으로 다음 단어를 의미 다음 토큰을 반환 이후 trim()이 필요하지 않습니다, 그래서 type 이미 손질한다.