Java分数计算器 - 通过try / catch分割ByByZeroMethod

时间:2015-10-22 12:19:14

标签: java try-catch netbeans-8 illegalargumentexception dividebyzeroexception

我正在开发一个程序,用户输入两个不同的分数,然后计算机通过Fraction方法运行它们来测试它们是否相等。赋值中的另一个步骤是抛出IllegalArgumentException以识别其中一个分母是否为0并依次重新启动程序。 Fraction和testFraction类如下:

分数类:

class Fraction {

    private int numerator;
    private int denominator;

    Fraction() {
        numerator = 0;
        denominator = 1;

    }

    Fraction (int num, int den) {
        numerator = num;
        denominator = den;
        if (denominator == 0){
            throw new IllegalArgumentException (
            "Denominator cannot be zero");
        }
    }

    public void setNum(int num){
        numerator = num;
    }

    public void setDen(int den){
        denominator = den;

        }

    public int getNum(){
        return numerator;
    }

    public int getDen(){
        return denominator;
    }

    public String toString() {
        return numerator + "/" + denominator;
        }

    public boolean equals(Fraction other){
    if (numerator * other.getDen() == denominator * other.getNum()){
            return true;
         } 
        else {
            return false;
        }
    }
}

testFraction类:

import java.util.Scanner;

public class testFraction {

public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in); 
    int a = 1;
    int b = 1;
    int c = 1;
    int d = 1;

    Fraction f1 = new Fraction(a, b);
    Fraction f2 = new Fraction(c, d);


    System.out.println("Enter the numerator of the first fraction: ");
    f1.setNum(keyboard.nextInt());

    System.out.println("Enter the denominator of the first fraction: ");
    f1.setDen(keyboard.nextInt());

    try{
        int fraction = a/b; 
    }
    catch (IllegalArgumentException e){
        System.out.println(e.getMessage);
        main(args);
    }

    System.out.println("\nEnter the numerator of the second fraction: ");
    f2.setNum(keyboard.nextInt());

    System.out.println("Enter the denominator of the second fraction: ");
    f2.setDen(keyboard.nextInt());

    System.out.println("\nFraction 1: " + f1);
    System.out.println("Fraction 2: " + f2);

    System.out.println("\nAre fractions equal? " + f1.equals(f2));

    System.out.println(("\nWould you like to run the counter with a different integer? \n(1 for YES - 0 for NO): "));
    int answer = keyboard.nextInt();

    if (answer == 1){
        System.out.println("\nLet's Rock 'n Roll! ");
        main(args);
    }

    else if (answer == 0){
        System.out.println("\nLater Dude! ");
        System.exit(0);
    }       
}
}

我觉得我在try / catch中工作不正常。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

在初始化Fraction时,您会抛出IllegalArgumentException,但是当您在testFraction中进行实际划分时,您会尝试捕获它。永远不会达到您的捕获,因为初始化时的异常将阻止代码到达错误的分区。你应该把你的try / catch放在创建Fractions的代码周围。

此外,您使用模拟值初始化您的分数:1。这不是非常有用,并且存在问题:您的构造函数将永远不会抛出其IllegalArgumentException,因为它是使用正确的值调用的。您应该在setDenominator中引发IllegalArgumentException,并从构造函数中调用它。