【发布时间】:2017-11-26 23:16:21
【问题描述】:
first : Java 具有处理异常的内置机制。使用 try 语句,我们可以测试代码块是否有错误。 catch 块包含说明如果发生异常时该怎么做的代码。
这个问题将考验你对 try-catch 块的了解。
您将获得两个整数 x,y 作为输入,您必须计算 x/y 。如果 and 不是位有符号整数或为零,则会发生异常,您必须报告它。阅读示例输入/输出以了解在出现异常时要报告的内容。
我已经通过了所有测试用例,它需要 java.lang.ArithmeticException: / 当用户输入 0 时为零。我的 catch 输出 System.out.println("java.util.InputMismatchException"); 我怎样才能通过最后一个测试用例?
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
try{
Scanner scan = new Scanner(System.in);
int input1 = scan.nextInt();
int input2 = scan.nextInt();
scan.close();
System.out.println(divideInput(input1,input2));
}catch(Exception e){
System.out.println("java.util.InputMismatchException");
}
}
public static int divideInput(int input1, int input2)
{
int sum;
sum = input1 / input2;
return sum;
}
}
【问题讨论】:
-
除非我们有输入,否则我们无法判断。你确定输入流中有两个整数吗?
-
您想打印 `System.out.println("java.util.InputMismatchException");` 中的所有异常类型并寻找打印此语句的替代方法吗?
-
sample in/out: Sample Input 1: 10 Hello Sample Output 1: java.util.InputMismatchException Sample Input 2: 10 0 Sample Output 2: java.lang.ArithmeticException: / by zero Sample Input 3 : 23.323 0 示例输出 3: java.util.InputMismatchException
-
就像我说的那样,它为 3 个测试用例打印了适当的输出,但是它没有捕获算术错误,也没有输出我需要的错误。这就是为什么我有点困惑。
-
您实际上是在告诉它打印“java.util.InputMismatchException”,这就是它要做的事情。