java - 三角形异常和非静态 toString()

标签 java

我正在编写一个程序,它以两个三角形作为实例并确定它们是否非法,如果非法则抛出异常。我的第一个问题是我试图抛出 TriangleException,而不是 Exception。我确信我只需要在某处更改或添加一些内容,这样它就不会在 Eclipse 中给我错误。

我的第二个问题是,当抛出Exception时,我尝试使用toString()方法输出非法三角形的边尺寸。它不断告诉我无法通过调用 toString() 来进行非静态引用。我在网上查看并尝试了一些不同的可能解决方案,但似乎都不起作用。

我在下面包含了我的两个类(class):

public class TriangleException extends Object {

    private double side1;
    private double side2;
    private double side3;

    public static void main(String[] args) throws Exception {
        try {
            TriangleWithException t1 = new TriangleWithException(1.5, 2, 3);
            System.out.println("Perimeter for t1: " + t1.getPerimeter());
            System.out.println("Area for t1: " + t1.getArea());

            TriangleWithException t2 = new TriangleWithException(1,2,3);
            System.out.println("Perimeter for t2: " + t2.getPerimeter());
            System.out.println("Area for t2: " + t2.getArea());
        }
        catch (TriangleException e){
            System.out.println("\nIllegal Triangle!!!");
            System.out.println(toString()); // trying to print the three sides of the illegal triangle here
        }
    }

    public double getSide1() {
        return side1;
    }

    public double getSide2() {
        return side2;
    }

    public double getSide3() {
        return side3;
    }
}

public class TriangleWithException extends Object {

    double side1, side2, side3;

    public TriangleWithException(double d, double i, double j) throws Exception {
        side1 = d;
        side2 = i;
        side3 = j;

        if (side1 >= side2 + side3)
            throw new TriangleException();
        else if (side2 >= side1 + side3)
            throw new TriangleException();
        else if (side3 >= side2 + side1)
            throw new TriangleException();
    }

    public double getArea() {
        double var = (side1 + side2 + side3)/2;
        double area = (var*(var-side1)*(var-side2)*(var-side3));
        return Math.sqrt(area);
    }

    public double getPerimeter() {
        return (side1+side2+side3);
    }

    public String toString() {
        return "\nSide 1 = " + this.side1 + "\nSide 2 = " + this.side2
            + "\nSide 3 = " + this.side3;
    }
}

最佳答案

您应该扩展Exception,而不是ObjectObject 不可抛出。如果您检查 javadoc 中的 Exception,您实际上会看到 Exception 本身实现了 Throwable。

关于java - 三角形异常和非静态 toString(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33084076/

相关文章:

java - Apache Tomcat 异常 - 打开的文件太多

java - 静态嵌套类线程安全 - java

java - 无法对基本类型 int 调用 getText()

java - 使用假日日历

Java:从源映射/复制到具有不同成员变量的目标

Java - 创建一个包含重复条目的 ZIP 文件

java - Android - 将图像的位图数组插入 SQLite 数据库

java - 使用 JAXB 解码通用列表

使用 Kryo 序列化对象时出现 java.lang.StackOverflowError

java - 如何在 Spring/Java 中使用 JSON 未命名值来使用 REST?