【发布时间】:2020-01-18 00:23:52
【问题描述】:
当使用资源实现 try 时,我通过 try 语句的 () 内的 Scanner sc = new Scanner(System.in) 创建一个 Scanner 对象。
在 try 块中,我提示用户输入一个数值,通过sc.nextLine() 读取它并利用parseDouble 将其转换为方法。
如果最初输入的值无效,我会使用 do-while 循环重新提示用户输入值。
但是,如果用户输入了无效值,输入流将关闭,NumberFormatException 会被捕获,但在 do-while 循环的第二次迭代期间,会抛出“No line found”NoSuchElementException 并在此后无限期地抛出'流关闭' java.io.IOException。
有没有办法在使用资源尝试时规避这种情况?
public static void main(String[] args) {
int x = 1;
do {
try (Scanner sc = new Scanner(System.in)) {
System.out.print("Enter a numeric value: ");
String input1 = sc.nextLine();
Double d1;
d1 = Double.parseDouble(input1);
System.out.print("Enter a numeric value: ");
String input2 = sc.nextLine();
Double d2;
d2 = Double.parseDouble(input2);
System.out.print("Choose an operation (+ - * /): ");
String input3 = sc.nextLine();
//sc.close();
switch (input3) {
case "+":
Double result = d1 + d2;
System.out.println("The answer is " + result);
break;
case "-":
Double result1 = d1 - d2;
System.out.println("The answer is " + result1);
break;
case "*":
Double result2 = d1 * d2;
System.out.println("The answer is " + result2);
break;
case "/":
Double result3 = d1 / d2;
System.out.println("The answer is " + result3);
break;
default:
System.out.println("Unrecognized Operation!");
break;
}
x++;
}
catch (NumberFormatException e){
System.out.println("Number formatting exception "+e.getMessage());
System.out.println("Enter a proper value");
}
catch (Exception e1){
System.out.println("Arbitrary error encountered"+e1.getMessage());
}
}
while(x==1);
}
【问题讨论】:
-
它正在工作,但您不想在 in 循环中执行此操作;因为关闭
Scanner也 关闭System.in。将try移到循环之外,您应该可以开始了。 -
关闭已打开的资源是个好习惯。但是,
Scanner包装了您没有打开的标准输入。一般的经验法则是“不要关闭你没有打开的东西”。 JVM打开了stdin,所以留给JVM关闭吧。 -
将 try 移到循环外将排除 catch 语句,如果输入了无效值,则会重新提示。
标签: java exception java.util.scanner inputstream try-with-resources