-6
public Dog[] dogList =
{
new Dog(1, 2, "Bacon"),
new Dog(3, 4, "Cheese"),
new Dog(8, 6, "Steak"),
new Dog(5, 6, "Lamb"),
new Dog(12, 14, "Caviar")
};
每當我運行我的程序我有一個StackOverflowError。我該如何解決這個堆棧溢出錯誤?
System.out.println(new Dog(2, 3, "hi").compareTo(new Dog(1, 2, "a")));
我通過該代碼運行它。 狗類的源代碼:
package Luka;
import java.util.Arrays;
public class Dog extends Animal implements Comparable<Dog>{
public void eat(String food)
{
System.out.println("The dog enjoyed his meal of " + food);
}
public int compareTo(Dog other)
{
if(this.age < other.age)
{
int returnNum = -1;
return returnNum;
}
else if(this.age > other.age)
{
int returnNum = 1;
return returnNum;
}
else
{
int returnNum = 0;
return returnNum;
}
}
public String toString(int weight,int age,String foodType)
{
return "The dog weighs "+weight+", is "+age+" years old, and eats "+foodType+" for dinner.";
}
public Dog(int weight, int age, String foodType)
{
this.weight = weight;
this.age = age;
this.foodType = foodType;
}
public Dog[] dogList =
{
new Dog(1, 2, "Bacon"),
new Dog(3, 4, "Cheese"),
new Dog(8, 6, "Steak"),
new Dog(5, 6, "Lamb"),
new Dog(12, 14, "Caviar")
};
}
請提供'Dog' class'源代碼。 –
到目前爲止您發佈的代碼沒有解釋該異常。很可能,您的構造函數或compareTo()調用會執行一些遞歸(它不應該這樣做)。 – GhostCat