我写了一段关于用户输入的操作符结果的代码,请解释一下这个字符输入是如何工作的,因为当我使用时
char operation = s.nextLine().charAt(0);
而不是
char operation = s.next().charAt(0);
Eclipse 显示错误。
代码-
System.out.println("Enter First Number:");
int a = s.nextInt();
System.out.println("Enter Second Number:");
int b = s.nextInt();
System.out.println("Which Operation you want to execute?");
s.hasNextLine();
char operation = s.next().charAt(0);
int result = 0;
switch (operation) {
case '+' :
result = a + b;
break;
case '-' :
result = a - b;
break;
case '*' :
result = a * b;
break;
case '/' :
result = a / b;
break;
case '%' :
result = a % b;
break;
default:
System.out.println("Invalid Operator!");
}
System.out.println(result);
s.close();
}
}
最佳答案
问题不是因为s.nextLine()
;相反,这是因为 s.nextInt()
。检查Scanner is skipping nextLine() after using next() or nextFoo()?了解更多信息。
使用
int a = Integer.parseInt(s.nextLine());
而不是
int a = s.nextInt();
我建议您创建一个实用函数,例如getInteger
创建于 this answer也可以处理特殊情况。
关于java - 字符(运算符)的扫描仪输入如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61302019/