三角形总是在java中说等边

时间:2014-03-20 04:29:15

标签: java if-statement boolean geometry

我不知道出了什么问题,但我的输出确定三角形的边有1.0,1.0,1.0并且始终是等边的。

public class Triangle
{
    // fields
    private double side1;

    private double side2;

    private double side3;

    // constructor
    public Triangle (double sideA, double sideB, double sideC)
    {
        sideA = side1;
            sideB = side2;
            sideC = side3;

            if(isTriangle(sideA, sideB, sideC) == false)
            {
                side1 = 1;
                side2 = 1;
                side3 = 1;
            }
    }

    // methods
    public double getSide1()
    {
        return side1;
    }

    public double getSide2()
    {
        return side2;
    }

    public double getSide3()
    {
        return side3;
    }

    public boolean isTriangle(double sideA, double sideB, double sideC)
    {
        if (side1 + side2 > side3 || side2 + side3 > side1 || side3 + side1 > side2)
        {
                return true;
        }

        else
        {
                return false;
        }
    }
    public boolean isEquilateral()
    {
        if(side1 == side2 && side2 == side3)
        {
                return true;
        }

        else
        {
                return false;
        }
    }

    public boolean isRight()
    {
        if (Math.pow (side1, 2) +  Math.pow (side2, 2) == Math.pow (side3, 2) ||
            Math.pow (side2, 2) +  Math.pow (side3, 2) == Math.pow (side1, 2) ||
            Math.pow (side3, 2) +  Math.pow (side1, 2) == Math.pow (side2, 2))
        {
            return true;
        }

        else
        {
            return false;
        }
    }
}

// A06 Triangle
import java.util.Scanner;

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

            double side1 = 0;
            double side2 = 0;
            double side3 = 0;

            System.out.print("Side1: ");
            side1 = input.nextDouble();
            System.out.print("Side2: ");
            side2 = input.nextDouble();
            System.out.print("Side3: ");
            side3 = input.nextDouble();
            System.out.println();

            Triangle myTriangle = new Triangle(side1, side2, side3);

            System.out.printf("Triangle( %.1f %.1f %.1f) %s\n", myTriangle.getSide1(),
            myTriangle.getSide2(), myTriangle.getSide3(), 
            myTriangle.isEquilateral() == true ? "is equilateral" :
            myTriangle.isRight() == true ? "is right" : "");
    }
}

1 个答案:

答案 0 :(得分:2)

以下是代码中的一个主要错误:

Triangle.java构造函数中,您将输入参数分配给字段,而不是将字段分配给输入参数。

sideA = side1;
sideB = side2;
sideC = side3;

我认为你的意思是:

side1 = sideA;
side2 = sideB;
side3 = sideC;

如果还没有,那么可能会在以后咬你的另一件事是浮点比较,如其他人的评论所述。您想要更改所有类似的比较:

Math.pow (side1, 2) +  Math.pow (side2, 2) == Math.pow (side3, 2)

比较看起来像这样:

Math.abs(Math.pow (side1, 2) +  Math.pow (side2, 2) - Math.pow (side3, 2)) < EPSILON

您可以将EPSILON定义为一些非常小的常量,例如1E-20