gpt4 book ai didi

java - 带混合分数计算器的 ArithmeticException

转载 作者:行者123 更新时间:2023-11-30 07:39:50 26 4
gpt4 key购买 nike

该程序可以正确计算带分数。我希望 while 循环在输入两个零后终止。但是,当我输入由空格分隔的两个零时,我得到“Exception in thread "main"java.lang.ArithmeticException:/by Zero at MixedFractions.main 等。我只是希望用户无法输入值a 和 be 一旦他们为两个变量都输入 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);
}
}

}

最佳答案

试试这个:

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();
}
}

关于java - 带混合分数计算器的 ArithmeticException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34841605/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com