圆自身异常不能制作半径异常

时间:2018-02-21 12:12:04

标签: java

异常无法出现,我显然不知道问题出在哪里。我想对圆半径做出自己的例外。例如,如果我的输入为负值,则需要显示异常。我做了3节课。 TestCircle.java,Circle.java和IllegalRadiusException.java

TestCircle.java

package circle;
public class TestCircle {

public static void main(String[] args) {

    double newRad;

    try {

        Circle A = new Circle();

        A.InputRadius();
        A.Calculation();
        newRad = A.getRadius();
        A.Result();
    } catch (IllegalRadiusException e) {
        System.out.println(e);
    }
}
}

Circle.java

package circle;

import java.util.Scanner;
public class Circle {

Scanner input = new Scanner(System.in);
private double radius;
private double area;

//this is consturctor method
public Circle() throws IllegalRadiusException {
    if (radius >= 0) {
        this.radius = radius;
        this.area = area;
    } else {
        throw new IllegalRadiusException("Radius Cannot be Negative");
    }
}

public void setRadius(double radius) {
    this.radius = radius;
}

public double getRadius() {
    return radius;
}

public void setArea(double area) {
    this.area = area;
}

public double getArea() {
    return area;
}

//------------------------------------------------------------//
public void Calculation() {
    area = 3.142 * radius * radius;
}

public void InputRadius() {
    System.out.print("Radius: ");
    radius = input.nextDouble();

}

public void Result() {
    System.out.println("");
    System.out.println("Radius: " + radius);
    System.out.println("Area: " + area);
}
}

IllegalRadiusException.java

package circle;
public class IllegalRadiusException extends Exception {

//Extra kena tambah 'extends Exception'
//WAJIB KENA LETAK untuk CREATE OWN EXCEPTION
public IllegalRadiusException() {

    super();

}

public IllegalRadiusException(String message) {

    super(message);
}
}

2 个答案:

答案 0 :(得分:1)

在您的代码中,构造函数只会在对象实例化时被调用一次。 您已在此构造函数中添加了异常检查。

要使您的示例按需工作,您还需要从 InpurRadius 方法中抛出异常,如果用户输入的值无效。

将您的方法更改为此。

public void InputRadius() throws IllegalRadiusException {
    System.out.print("Radius: ");
    double entered_radius = input.nextDouble();
    if (entered_radius >= 0) {
        this.radius = entered_radius;
        this.area = area;
    } else {
        throw new IllegalRadiusException("Radius Cannot be Negative");
    }

}

答案 1 :(得分:0)

您没有在构造函数中将值传递给radius,因此它未初始化(0)。所以if语句总是会从0 == 0 :)开始传递。通过

public Circle(double radius) // something like this

并将其在构造函​​数中分配给radius