ArithmeticException with Mixed Fractions计算器

时间:2016-01-17 17:53:32

标签: java exception

此程序正确计算混合分数。我希望while循环在我输入两个零后终止。但是,当我输入两个由空格分隔的零时,我得到“线程中的异常”主“java.lang.ArithmeticException:/在MixedFractions.main等处为零。我只是希望用户无法输入值a并且一旦他们为两个变量输入0。谢谢

import java.util.Scanner;
 public class MixedFractions  {
public static void main (String [] args)
{

    Scanner scan = new Scanner(System.in);
    int a = scan.nextInt(); int b = scan.nextInt();
    int c = Math.abs(a / b);
    int d = c * b;
    int e = c * b;
    int f = a - e;
    while ( a != 0 && b!= 0)
    {


        if(c == 0)
        {
            System.out.println(c + " " + a  + " / " + b);
        }
        else if(d == a)
        {
            a = 0;
            System.out.println(c + " " + a  + " / " + b);

        }
        else if( c != a)
        {
             e = c * b;
             f = a - e;
            System.out.println(c + " " + f  + " / " + b);
        }
        a = scan.nextInt(); b = scan.nextInt();
        c = Math.abs(a/b);
    }
}

}

1 个答案:

答案 0 :(得分:1)

试试这个:

public static void main (String [] args) {

    Scanner scan = new Scanner(System.in);
    int a = scan.nextInt(); 
    int b = scan.nextInt();
    while ( a != 0 && b!= 0) {
        int c = Math.abs(a / b);
        int d = c * b;
        if(c == 0) {
            System.out.println(c + " " + a  + " / " + b);
        } else if(d == a) {
            a = 0;
            System.out.println(c + " " + a  + " / " + b);
        } else if( c != a) {
            int e = c * b;
            int f = a - e;
            System.out.println(c + " " + f  + " / " + b);
        }
        a = scan.nextInt(); 
        b = scan.nextInt();
    }
}