0
import java.util.Scanner;
import java.util.InputMismatchException;
public class Main
{
public static int quotient(int a, int b) throws ArithmeticException
{
return a/b;
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
boolean continueLoop = true;
do
{
try
{
System.out.print("Enter integer numerator: ");
int numerator = scan.nextInt();
System.out.print("Enter integer denomiantor: ");
int denominator = scan.nextInt();
int result = quotient(numerator, denominator);
System.out.println("Result: " + numerator + "/" + denominator
+ " = " + result);
continueLoop = false;
}
catch (InputMismatchException inputMismatchException)
{
System.err.println("\nException: " + inputMismatchException);
scan.nextLine();
System.out.println("\nSolution: Must enter an integer");
}
catch (ArithmeticException arithmeticException)
{
System.err.println("\nException" + arithmeticException);
System.out.println("Solution: Zero is an invalid denominator");
}
} while (continueLoop);
}
}
輸出:排序錯誤輸出的
Enter integer numerator: 5
Enter integer denomiantor: 0
Solution: Zero is an invalid denominator
Enter integer numerator:
Exceptionjava.lang.ArithmeticException:/by zero
我對爲什麼在最後顯示的System.err.println
消息混淆?而且如果我遺漏了scan.nextLine();
,爲什麼會出現無限循環?