1
此程序正確計算混合分數。我希望while循環在我輸入兩個零時終止。然而,當我輸入兩個零分隔的空間時,我得到「異常在線程」主要「java.lang.ArithmeticException:/由零在MixedFractions.main等我只是想讓用戶無法輸入值和是一旦他們兩個變量輸入0謝謝ArithmeticException與混合分數計算器
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);
}
}
}
之前'INT C = Math.abs(A/b);'添加你想要的:'if(a == 0 && b == 0){... BOOM ...}' –
你應該考慮捕捉ArithmeticException或者那個錯誤wo在'b'輸入'0'的其他時間仍然會出現。 –