(java.lang.StackOverflowError) 我该如何解决?

(java.lang.StackOverflowError) how do i solve it?

我正在编写一个基于二次方程的程序,在我看来一切都很好,而且我所看到的没有语法或逻辑错误,而且 Eclipse 在 运行 之前没有检测到任何错误。 这是代码的输出: 线程异常 "main" java.lang.WhosebugError 在 QuadraticEquation.getDiscriminant(QuadraticEquation.java:33) 注意它会像这样继续大约 50 行左右

public class QuadraticEquation {
    private double a;
    private double b;
    private double c;
    public QuadraticEquation() {  
    double a = 0;
    double b = 0;
    double c = 0;
    }

    public QuadraticEquation(double newA, double newB, double newC) {
        a = newA;
        b = newB;
        c = newC;
    }

    public double discriminant1 = Math.pow(b, 2) - 4 * a * c;
    public double discriminant2 = Math.pow(b, 2) - 4 * a * c;

    public double getA() {
    return getA();
    }
    public double getB() {
    return getB();
    }   
    public double getC() {
    return getC();
    }

    public double getDiscriminant() {
    double discriminant = (b * 2) - (4 * a * c);
        return getDiscriminant();
    }

    public double getRoot1() {
        double r1 = (-1*b) + Math.sqrt(discriminant1) / (2*a);
        return getRoot1();

    }
    public double getRoot2() {
        double r2 = (-1*b) - Math.sqrt(discriminant2) / (2*a);
        return getRoot2();
    }   

    public void setA(double newA1) {
        a = newA1;
    }
    public void setB(double newB1) {
        b = newB1;
    }
    public void setC(double newC1) {
        c = newC1;
    }
}
import java.util.Scanner;

public class TestEquation {

    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    QuadraticEquation Quadratic = new QuadraticEquation();



        System.out.println("Please enter the values of the following variables: ");

        System.out.println("a: ");
        Quadratic.setA(input.nextDouble());

        System.out.println("b: ");
        Quadratic.setB(input.nextDouble());

        System.out.println("c: ");
        Quadratic.setC(input.nextDouble());

        if (Quadratic.getDiscriminant() < 0) {

            System.out.println("The equation has the following roots:");

            System.out.println("The first one is " + Quadratic.getRoot1());

            System.out.println("The second one is " + Quadratic.getRoot2());


        }
        else if (Quadratic.getDiscriminant() == 0) { 
            System.out.println("The equation has one root:");

            System.out.println(Quadratic.getRoot1());

        }

        else {

        System.out.println("The equation has the no real roots");

        return;

        }
    }

}

你的错误是这里的无限递归:

public double getDiscriminant() {
    double discriminant = (b * 2) - (4 * a * c);
    return getDiscriminant();
}

这个函数会无限地调用自己,直到堆栈溢出。我相信您想 return 变量 discriminant 来代替?

与您的函数 getRoot1getRoot2getAgetBgetC.

相同