Java while循环结合if/else时else分支无限循环问题求助
问题原因及解决方案
核心问题:无限循环的根源
当用户输入非整数内容时,Scanner的hasNextInt()会返回false,但无效输入并未被从输入缓冲区中移除。这导致每次循环都会重复检测到同一个无效输入,进而触发无限循环。
另外还有两个次要问题:
- 运算完成后
charCheck和numCheck未重置为true,程序无法进入下一轮的运算符和数字输入流程 - 缺少除数为0的校验,会触发运行时异常
修改后的代码
import java.util.Scanner; public class mainClass { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean charCheck; //for verifying user arithmetic input boolean numCheck; //for verifying user int input boolean sysCheck = true; //for program outer while loop int n1 = -1; //user entered number 1 int n2 = -2; //user entered number 2 char x = ' '; //user entered arithmetic operator while (sysCheck == true) { charCheck = true; // 每次循环重置运算符校验标志 while (charCheck == true) { System.out.println("Please enter either +, -, *, / to proceed. Enter x to end the program"); x = input.next().charAt(0); switch(x) //check input validity for x before the program proceeds { case '+': case '-': case '*': case '/': System.out.println(x); charCheck = false; break; case 'x': System.exit(0); break; default: System.out.print("That is an invalid entry. "); } } System.out.println("Now, please enter 2 numbers, separated by a space: "); numCheck = true; // 每次循环重置数字校验标志 while(numCheck) { if(input.hasNextInt()) { n1 = input.nextInt(); // 校验第二个输入是否也是整数,避免只输入一个有效整数后卡住 if(input.hasNextInt()){ n2 = input.nextInt(); System.out.println(n1 + " " + n2); numCheck = false; } else { System.out.print("That is an invalid entry. "); input.next(); // 消费无效输入 } } else{ System.out.print("That is an invalid entry. "); input.next(); // 关键:消费掉无效的非整数输入 } } switch(x) //calculate and output result { case '+': System.out.println("\nThe result is: " + (n1 + n2)); break; case '-': System.out.println("\nThe result is: " + (n1 - n2)); break; case '*': System.out.println("\nThe result is: " + (n1 * n2)); break; case '/': // 添加除数为0的校验 if(n2 == 0){ System.out.println("\nError: Cannot divide by zero."); } else { System.out.println("\nThe result is: " + (n1 / n2)); } break; } } } }
关键修改点说明
- 解决无限循环:在
else分支添加input.next(),将缓冲区中的无效输入消费掉,让Scanner可以接收新的输入 - 重置标志位:每次进入外层循环时,重置
charCheck和numCheck为true,确保程序可以重复执行输入流程 - 增强鲁棒性:
- 校验第二个输入是否为整数,避免用户输入一个有效整数加一个无效内容时卡住
- 添加除数为0的判断,避免运行时异常
- 细节优化:修正了
seperated的拼写错误,输出结果前添加换行符提升可读性
内容的提问来源于stack exchange,提问作者Gary L.
相关产品推荐
相关产品推荐

