2017-03-28 13 views
-3

私のチェック方法がうまくいかない理由を誰かが説明できますが、私は間違いがどこにあるのかわからないためです。Javaチェックメソッドの継承

Dog dogArray = new Dog(); 
    Animal[] animals = new Animal[5]; 
    animals [0] = new Dog(); 
    animals [1] = new Cat(); 
    animals [2] = new Wolf(); 
    animals [3] = new Hippo(); 
    animals [4] = new Lion(); 
     for (int i = 0; i < animals.length; i++) { 
     animals[i].eat(); 
     animals[i].makeNoise(); 
     animals[i].testPolymorphism(); 
     public void checkAnimals() { 
      if (dogArray.equals(animals[i])) { 
          System.out.println("DogArray matches Dog i" + i); 
        } 
      System.out.println("DogArray doesn't match any animal"); 

     } 
    } 
+2

別の方法で宣言しています。それはうまくいかないでしょう。 – Kayaman

+0

関数内で関数を作成することはできません。 – JediBurrell

+2

私はあなたのコード内のランダムな場所でメソッドを宣言しようとしていますが、確かにjavaではありません。 –

答えて

1

forループ内にcheckAnimalコードを記述することができます。これにより、新しいメソッドを記述して、期待される結果を得る必要はありません。

Dog dog = new Dog(); 
    Animal[] animals = new Animal[5]; 
    animals [0] = new Dog(); 
    animals [1] = new Cat(); 
    animals [2] = new Wolf(); 
    animals [3] = new Hippo(); 
    animals [4] = new Lion(); 

    for (int i = 0; i < animals.length; i++) { 
     animals[i].eat(); 
     animals[i].makeNoise(); 
     animals[i].testPolymorphism(); 

     if (dog.equals(animals[i])) { 
      System.out.println("DogArray matches Dog i" + i); 
     }else{ 
      System.out.println("DogArray doesn't match any animal"); 
     } 
    } 
0

これはあなたが達成しようとしていたものだと私は信じています。

public void main() { 
     //Declarations 
     Dog dogArray = new Dog(); //Could call this just "dog" 
     Animal[] animals = new Animal[5]; //"animalsArray" could be a suitable name 

     //Populate array 
     animals [0] = new Dog(); 
     animals [1] = new Cat(); 
     animals [2] = new Wolf(); 
     animals [3] = new Hippo(); 
     animals [4] = new Lion(); 

     //call function which you were trying to declare inside a function 
     checkAnimals(animals, dogArray); 
    } 

    public void checkAnimals(Animals animals, Dog dogArray) { 
    //Loop through array 
    for (int i = 0; i < animals.length; i++) { 
     //Process each animal 
     animals[i].eat(); 
     animals[i].makeNoise(); 
     animals[i].testPolymorphism(); 

     //Check if current animal is the dog 
     if (dogArray.equals(animals[i])) { 
      System.out.println("DogArray matches Dog i" + i); 
     } else { 
      System.out.println("DogArray doesn't match current animal"); 
     } 
    } 
    }