2017-03-28 111 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"); 
     } 
    } 
    }