3 回答
TA贡献1772条经验 获得超8个赞
既然你已经表现出了努力,但你似乎也是Java的新手,我正在尝试纠正你的代码。通常,不建议用于这种低水平的校正。
我们需要在捕获它之前抛出一个异常 - 这就是你周围的情况 - 。NegativeValueException
我假设变量 &类型 - , &是声明和定义的。NegativeValueExceptioninvalidInputkeyboard
我已经提供了示例代码,对您提出的代码进行了最小的更改,尽管您提出的问题可以通过更好的代码来解决。
do{
invalidInput=false;
try{
System.out.print("Please enter a positive value for the numerator: ");
int numerator = keyboard.nextInt();
System.out.print("Please enter a positive value for the denominator: ");
int denominator = keyboard.nextInt();
if(numerator<0 && denominator <0){
throw new NegativeValueException();
}else if (numerator >=0 && denominator >= 0){
int quotient = numerator / denominator;
System.out.println();
System.out.print("The result of integer division is: ");
System.out.println(quotient);
System.out.println();
}
} catch(InputMismatchException e){
System.out.println("Enter only numbers.");
invalidInput = true;
}catch(NegativeValueException e){
System.out.println("no negative values.");
invalidInput = true;
}catch(ArithmeticException e){
System.out.println("Division by zero.");
invalidInput = true;
}
}while (invalidInput);
TA贡献1818条经验 获得超11个赞
Scanner s = new Scanner(System.in);
do {
try {
System.out.print("Please enter a positive value for the numerator: ");
int numerator = s.nextInt();
System.out.print("Please enter a positive value for the denominator: ");
int denominator = s.nextInt();
int quotient = numerator / denominator;
} catch (InputMismatchException e) {
System.out.println("InputMismatchException " + e);
System.exit(0);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException " + e);
System.exit(0);
} catch (Exception e) {
System.out.println("NegativeValueException " + e);
System.exit(0);
}
} while (true);
TA贡献1876条经验 获得超6个赞
实际上,问题是你在外面做数学运算,比如说如果它抛出一个程序通过这些检查:try-blockexception
if (numerator >=0 && denominator >= 0) // false as there was exception
else if(numerator<0 && denominator <0) // false as there was exception
else
invalidInput = true; //gets executed
执行每个异常并因此中断 .将数学移入内部invalidInput = truedo-while looptry-block
试试这个代码:
do
{
try
{
System.out.print("Please enter a positive value for the numerator: ");
numerator = keyboard.nextInt();
System.out.print("Please enter a positive value for the denominator: ");
denominator = keyboard.nextInt();
if (numerator >=0 && denominator >= 0)
{
quotient = numerator / denominator;
}
else if(numerator<0 && denominator <0)
{
throw new NegativeValueException();
}
else
invalidInput = true;
System.out.println();
System.out.print("The result of integer division is: ");
System.out.println(quotient);
System.out.println();
}
catch(InputMismatchException e)
{
System.out.println("Enter only numbers.");
}
catch(NegativeValueException e)
{
System.out.println("no negative values.");
}
catch(ArithmeticException e)
{
System.out.println("Division by zero.");
}
}while (invalidInput);
添加回答
举报