2017-04-16 4 views
1

コンストラクタで提供した検証チェックを使用して、クラス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; 
    } 
} 

答えて

0

whileループの条件が正しくありません。 typeが少なくとも1つの文字列と等しくない場合は、次に進みます。さて、typeは、これらの文字列のうちの2つ以上の文字列と等しくないため、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が既に削除されます。

関連する問題