main java.lang.ArithmeticException:/ by Zero

时间:2016-02-22 10:45:52

标签: java

我尝试了使用throw new方法表示不能除以零的不同方法。

public class FractionDemo
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        Fraction f1 = new Fraction(), f2 = new Fraction(); 

        System.out.print("Enter the numerator for the target fraction:"); 
        int a = scan.nextInt(); 

        System.out.print("Enter the denominator for the target fraction:"); 
        int b = scan.nextInt(); 

        System.out.print("Enter the numerator for the next fraction to test:"); 
        int n = scan.nextInt(); 

        System.out.print("Enter the denominator for the next fraction to test:"); 
        int d = scan.nextInt(); 

        if(f1.equals(f2))
            System.out.print("The fraction you just entered equals the first fraction of" + f1 + "."); 
        else 
            System.out.print("The fraction you just entered does not equal the first fraction of" + f1 + ".");
    }
}

也是这个

public class Fraction
{
    // set variables 
    private int numerator, denominator, fraction; 

    public void Fraction()
    {
        numerator = 0; 
        denominator = 1;
    }

    public void Fraction(int n, int d)
    {
        numerator = n; 
        denominator = d;
    }

    // Numerator
    public void setNumerator(int n)
    {
        numerator = n; 
    }

    public void setDenominator(int d)
    {
        denominator = d;

    }
    public void setCalculation(int n, int d)
    {
        fraction = numerator/denominator;
        if (denominator == 0)
        {
            throw new IllegalArgumentException("Argument 'divisor' is 0");
        }
    }   

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

    public boolean equals(Fraction f)
    {
        return ((numerator/denominator) == (f.numerator/f.denominator));
    }
}

当我运行程序时。我在Fraction.equals(Fraction.java:52)和FractionDemo.main(FractionDemo.Java:31)中得到“线程中的异常”主“java.lang.ArithmeticException:/ 0”。

第一个将我引导到公共布尔值。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

你应该在除以之前检查零:

 public void setCalculation(int n, int d)
            {

               if (denominator == 0)
               {
                   throw new IllegalArgumentException("Argument 'divisor' is 0");
               }

               fraction = numerator/denominator;
            }  

此外,需要在equals()方法中进行相同的检查。