Java 错误:构造函数中"Exception in thread "主要" java.lang.StackOverflowError"问题



我真的很困,希望有人能帮助我。我阅读了又读,但仍然不明白如何修复我的堆栈溢出错误。我知道它在我的构造函数中,但我不知道如何修复它。

我正在创建一个名为FractionBottle的派生类,它扩展了Bottle类。作为私有数据成员的 FractionBottle 类:Fraction myFraction = new Fraction();这是我在瓶子类中的构造函数:

 public class Bottle

    private final int MAX_PILLS = 120;
    private int pillsInBottle;
public Bottle()
{
    pillsInBottle = 0;

}

以下是我在FractionBottle课程中的内容:

public class FractionBottle extends Bottle
{
    Fraction myFraction = new Fraction();

    public FractionBottle()
    {
        super();
        myFraction.getNumerator();
        myFraction.getDenominator();
    }


    public FractionBottle(int wholeValue, int num, int den)
    {
        super(wholeValue);
        myFraction.set(num, den);;
    }
    public void read()
    {
        super.read();
        System.out.println("Pleas enter value for fraction part:");
        myFraction.read();
    }
    public FractionBottle add(FractionBottle other)
    {
        FractionBottle sumOfBottles = new FractionBottle();
        sumOfBottles = this.add(other);
        sumOfBottles.myFraction = this.myFraction.add(other.myFraction);

        return (sumOfBottles);
    }

这是我正在使用的演示:

public class FractionBottleDemo 
{
    public static void main (String args[])
    {

        FractionBottle fbl1 = new FractionBottle();
        FractionBottle fbl2 = new FractionBottle();
        FractionBottle fbl3 = new FractionBottle();
        System.out.println("Enter info for whole value for fbl1: ");
        fbl1.read();
        System.out.println("Enter infor for whole value for fbl2: ");
        fbl2.read();
        System.out.println(fbl1);
        System.out.println(fbl2);

         fbl3 = fbl1.add(fbl2);

    }
}

我真的被困在课堂上,我已经做了几天了。我收到以下错误:

  Exception in thread "main" java.lang.StackOverflowError
    at FractionBottle.<init>(FractionBottle.java:7)
    at FractionBottle.add(FractionBottle.java:32)

最后的林重复了好几遍...

请告诉我如何解决这个问题!我知道它会进入一个无限递归循环。但我不知道如何解决它。我的 FractionBottle 类中的 add 方法必须返回一个 FractionBottle。

谢谢!!!!

看起来您在 add 方法中有一个无限递归调用。

sumOfBottles = this.add(other);
所有递归

函数都需要检查才能脱离递归调用。

因为,您想调用瓶子的add方法。

将上面的行替换为

sumOfBottles = super.add(other);

显然错误就在这里:

public FractionBottle add(FractionBottle other){
    ...
    sumOfBottles = this.add(other);
    ...
}

因为您正在从此方法调用add方法,这会导致无限数量的递归调用,然后,您的 StackOverflowError

也许你想做的是调用 Bottle 的add方法,即:

public FractionBottle add(FractionBottle other){
        ...
        Bottle sumOfBottles = new FractionBottle();
        sumOfBottles = super.add(other);
        ...
    }

这更安全,不会导致无限循环

相关内容

最新更新