[英]Why does my first print statement print twice when the loop restarts?
当我输入第一个或第二个数字值的无效输入时"Enter an operation (+, -, *, /, quit)"
为什么"Enter an operation (+, -, *, /, quit)"
打印两次? "Enter an operation (+, -, *, /, quit)"
无效后"Enter an operation (+, -, *, /, quit)"
循环应重新启动并打印"Enter an operation (+, -, *, /, quit)"
。
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int i = 1;
while(i > 0){
String operation = "";
int firstInt = 0;
int secondInt = 0;
double firstDouble = 0.0;
double secondDouble = 0.0;
int intAnswer = 0;
double answer = 0.0;
boolean first = false;
boolean second = false;
System.out.println("Enter an operation (+, -, *, /, quit)");
operation = scnr.next();
if(operation.equals("+")|| operation.equals("-") || operation.equals("*") || operation.equals("/")){
System.out.println("Enter first numeric value");
if(scnr.hasNextInt()){
firstInt = scnr.nextInt();
first = true;
}else if(scnr.hasNextDouble()){
firstDouble = scnr.nextDouble();
}
else{
continue;
}
System.out.println("Enter second numeric value");
if(scnr.hasNextInt()){
secondInt = scnr.nextInt();
second = true;
}else if(scnr.hasNextDouble()){
secondDouble = scnr.nextDouble();
}
else{
continue;
}
}
else if(operation.equals("quit")){
System.exit(0);
scnr.close();
break;
}
}
}
使用Scanner.nextInt()
等会使扫描器缓冲区保持打开状态,因为它不会占用整行,而是仅将最接近的原始值和该行的其余部分存储在扫描器缓冲区中,并且仅由新的行调用使用。 这会导致很多意外情况,并且难以解决错误。
使用扫描仪获取原始数据类型时的更好做法是使用
double yourDouble = Double.parseDouble(Scanner.nextLine());
//for int you use Integer.parserInt(Scanner.nextLine()
这样一来,扫描程序就消耗了整行,并且缓冲区中没有存储任何内容,而且您不会因输出/输入流出现异常而感到头疼。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.