我如何制作TriangleWithException对象?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我如何制作TriangleWithException对象?相关的知识,希望对你有一定的参考价值。

我正在这里做一些作业。到目前为止,这是我的代码。我做了一个Triangle类,GeometricaObject类和IllegialTriangleException类。作业说要创建一个TriangleWithException对象,将值1.5、2和3传递给构造函数,并创建另一个对象,将值1、2和3传递到这里。到目前为止,这是我的代码:

public class Triangle extends GeometricObject 
    private double side1;
    private double side2;
    private double side3;

    public Triangle() 
        this.side1 = 1;
        this.side2 = 1;
        this.side3 = 1;
    

    public double getArea() 
        return (side1 + side2 + side3) / 2;
    

    public double getPerimeter() 
        return side1 + side2 + side3;
    
    public double getSide1()
        return side1;
    
    public double getSide2()
        return side2;
    
    public double getSide3()
        return side3;
    
    public void setSide1() 
        this.side1 = side1;
    
    public void setSide2() 
        this.side2 = side2;
    
    public void setSide3() 
        this.side3 = side3;
    
    public String toString() 
        return "Triangle: Side 1 = " + side1 + " Side 2 = " + side2 + " Side 3 = " + side3;
    

class IllegalTriangleException extends Exception 
    private double side = 1.0;
    public IllegalTriangleException(double side) 
        super(side + " is larger than other two combined");
    
    public double getSide1() 
        return side;
    

public class GeometricObject 
    private String color = "White";
    private boolean filled;
    private java.util.Date dateCreated;

    public GeometricObject() 
        dateCreated = new java.util.Date();
    

    public GeometricObject(String color, boolean filled) 
        dateCreated = new java.util.Date();
        this.color = color;
        this.filled = filled;
    

    public String getColor() 
        return color;
    

    public void setColor(String color) 
        this.color = color;
    

    public boolean isFilled() 
        return filled;
    

    public void setFilled(boolean filled) 
        this.filled = filled;
    

    public java.util.Date getDateCreated() 
        return dateCreated;
    
    public String toString() 
        return "Created on " + dateCreated + "\n color: " + color + " and filled ";
    

有人可以帮我吗?确保它具有尝试捕获块。

答案

您应该给新类的构造方法抛出异常的可能性。只需将两面作为参数,然后可以使用If进行检查,并在需要时抛出异常。

public TriangleWithException(double side1, double side2, double side3) throws IllegalTriangleException 
      if (side1 > side2 + side3)
         throw new IllegalTriangleException(side1)
      
      // Add if's for other sides

      this.side1 = side1;
      this.side2 = side2;
      this.side3 = side3;
    

以上是关于我如何制作TriangleWithException对象?的主要内容,如果未能解决你的问题,请参考以下文章

如何制作多表头

如何制作EXE文件图标

如何制作粉红噪声发生器?

我正在用 HTML 制作一个应用程序,我需要制作一个应用程序图标。如何实现图标? [关闭]

如何制作班级模板

如何检查我在 Django 中制作的模型中是不是存在用户?