如何使用我在Scanner类的另一个类中创建的方法为该方法提供数据?

时间:2017-10-26 19:48:54

标签: java

我试图让用户输入三角形的基数和高度,并用它们计算斜边。

我得到的错误是Exception in thread "main" java.lang.StackOverflowError,并指向我询问用户的第42行。

下面是实际的代码:

public class RTTriangle {
     private double base;        // properties
     private double height;
     private double hypotenuse;

public RTTriangle()         // Constructors
{
    base = 2;
    height = 0;
}
public RTTriangle(double BASE2, double HEIGHT2)         // Constructors
{
    base = BASE2;
    height = HEIGHT2;
}

public void setBase(double BasE)       // setters
{
    base =  BasE;
}

public void setHeight(double Height)
{
    height = Height;
}

public double getBase()           // getters
{
    return base;
}

public double getHeight()
{
    return height;
}

public double getHypotenuse(double x, double y)
{
    hypotenuse = Math.sqrt(Math.pow(base, 2.0) + Math.pow(height, 2.0));
    return hypotenuse = getHypotenuse(base, height);
}

public double getArea()
{
    double area;
    area = base * height;
    return area;
}

public double getPerimeter()
{
    double Perimeter;
    Perimeter = height + base + this.getHypotenuse();
    return Perimeter;
}

}

我试图搞砸它,但我似乎仍然无法工作。 这就是我把它称为我的其他课程的方式

import java.util.Scanner;

public class RTTriangleDemo {

public static void main(String[] args)
{

    double base;
    double height;

    Scanner SCAN = new Scanner(System.in);
    RTTriangle TRI1 = new RTTriangle();
    RTTriangle TRI2 = new RTTriangle();

    System.out.print("Enter the base of the Triangle: " );
    base = SCAN.nextDouble();
    System.out.print("Enter the length of the Triangle: " );
    height = SCAN.nextDouble();

    System.out.print("The hypotenuse is: " + TRI1.getHypotenuse(base, height));

如果有人能帮助我,我将非常感激。

2 个答案:

答案 0 :(得分:2)

在以下方法中:

public double getHypotenuse(double x, double y)
{
    hypotenuse = Math.sqrt(Math.pow(base, 2.0) + Math.pow(height, 2.0));
    return hypotenuse = getHypotenuse(base, height);
}

将最后一行更改为

return hypotenuse;

其余的是递归调用,您不需要。它将一直无限地调用自己,直到你的堆栈空间不足,导致你的程序崩溃。

与您的问题无关,但您有一个构造函数,它取三角形的基数和高度。我考虑使用它,因此您不必将这些值传递给hypotenuse方法。

答案 1 :(得分:0)

getHypotenuse方法是递归的:

double getHypotenuse(double x, double y) {
    hypotenuse = Math.sqrt(Math.pow(base, 2.0) + Math.pow(height,2.0));
    return hypotenuse = getHypotenuse(base, height); // <-- recursion
}

此外,它是无限递归的。相反,它应该是:

double getHypotenuse(double x, double y) {
    hypotenuse = Math.sqrt(Math.pow(base, 2.0) + Math.pow(height,2.0));
    return hypotenuse;
}