为什么我的Java while循环仅对部分嵌套if语句分支正常运行
问题根因
这是Java Scanner 类的输入缓冲区换行残留导致的问题:
nextInt()方法仅读取输入流中的整数内容,不会处理用户输入完数字按下回车产生的\n换行符,该换行符会残留在输入缓冲区中。- 待当前分支执行完成回到循环开头,调用
input.nextLine()时会直接读取到残留的换行符,得到空字符串,匹配不到任何合法选项,因此直接触发非法选项提示,随后重新进入循环。 - 选项3能正常运行的原因是输入字符串用的也是
nextLine(),会将换行符一同读取处理,没有残留内容。
修复方案
两种可选修复方式:
方案1:手动清理残留换行
在所有nextInt()调用结束后,新增一行input.nextLine()手动吃掉缓冲区残留的换行符即可,同时可以删除无效判断width%1!=0(int类型对1取模结果永远为0,该判断永远不生效)。
修改后示例代码:
while(flag){ System.out.println("Select an option from the menu below:" + "\n1: Display consecutive numbers in a right triangle" + "\n2: Determine if a number is divisible by 3" + "\n3: Determine the number of periods and spaces in a string" + "\n4: Display a right triangle of astrisks" + "\n5: Exit"); String option = input.nextLine(); if(option.equals("1")){ System.out.println("Enter number of columns: "); int width = input.nextInt(); input.nextLine(); // 新增:清理换行残留 while(width<=0){ System.out.println("Invalid input! Please enter a positive width."); width = input.nextInt(); input.nextLine(); // 新增:清理换行残留 } numOfColumns(width); } else if(option.equals("2")){ System.out.println("Enter number:"); int num = input.nextInt(); input.nextLine(); // 新增:清理换行残留 divisibleBy3(Math.abs(num)); } else if(option.equals("3")){ System.out.println("Enter string:"); String sentence = input.nextLine(); System.out.println("Number of periods and spaces: " + periodsAndSpaces(sentence) + "\n"); } else if(option.equals("4")){ System.out.println("Enter the width of the triangle:"); int length = input.nextInt(); input.nextLine(); // 新增:清理换行残留 rightTriangle(length, ""); } else if(option.equals("5")){ flag = false; } else{ System.out.println("That is not a valid option!"); } }
方案2:统一使用nextLine读取
所有输入都用nextLine()读取,需要数值类型时自行做类型转换,从根源避免换行残留问题,同时可以兼容非数字输入的异常处理,健壮性更强:
// 示例:读取数值的逻辑替换 System.out.println("Enter number of columns: "); String widthStr = input.nextLine(); try{ int width = Integer.parseInt(widthStr); if(width <= 0){ System.out.println("Invalid input! Please enter a positive width."); continue; } numOfColumns(width); }catch(NumberFormatException e){ System.out.println("Invalid input! Please enter a valid integer."); }
内容的提问来源于stack exchange,提问作者user17080770
相关产品推荐
相关产品推荐

