第一篇帖子对我来说很容易。我知道这对我来说是一个简单的疏忽,但我无法直观地看到这里发生了什么,所以任何洞察都会非常感激。
问题是我目前的代码是反复打印“无效的数字格式。请重试。”输入错误的操作数进入控制台,即“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();
}
答案 0 :(得分:2)
如果发生故障,.next
方法不会消耗任何输入。这意味着下一次循环它们只会读取相同的错误输入并以相同的方式失败。
要解决此问题,只需在发生错误时调用.nextLine()
即可完全跳过违规输入行。
来自Scanner.nextDouble()
的文档:
如果翻译成功,扫描仪将超过匹配的输入。