第一篇文章,所以对我容易。我知道这只是我的简单疏忽,但我无法直观地了解此处实际发生的情况,因此,不胜感激。
问题是我当前的代码反复打印“无效的数字格式。请重试。” 在输入不正确的操作数(即“ 2a + 2”)时进入控制台,在这种情况下,我特别被要求使用nextDouble和next。
尝试自行修复此问题后,我被认为可以通过调用nextDouble和next来相互调用,这需要使用nextLine,但是我仍然不明白为什么会这样。
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean repeat = true;
double n1,n2;
String op;
System.out.print("Enter a simple mathematical formula: ");
while(repeat){
try{
n1 = in.nextDouble();
op = in.next();
n2 = in.nextDouble();
switch(op){
case "+":
System.out.println("Result: " + (n1 + n2));
break;
case "-":
System.out.println("Result: " + (n1 - n2));
break;
case "/":
System.out.println("Result: " + (n1 / n2));
break;
case "*":
System.out.println("Result: " + (n1 * n2));
break;
default:
System.out.println("Invalid Operator. Try again.");
continue;
}
repeat = false;
}catch(InputMismatchException e){
System.out.println("Invalid number format. Try again.");
}
}
in.close();
}
.next
如果发生故障,这些方法不会消耗任何输入。这意味着下一次遍历循环时,他们将读取相同的错误输入并以相同的方式失败。
要解决此问题,只需.nextLine()
在发生错误时调用即可完全跳过有问题的输入行。
从以下文档中Scanner.nextDouble()
:
如果翻译成功,则扫描程序将前进经过匹配的输入。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句