Java中依赖Scanner布尔输入的While循环重复执行问题排查
问题分析与修复方案
问题根源
scan.nextBoolean()只会读取输入的布尔值(true/false),但你输入完后按回车键产生的换行符会留在输入缓冲区里。进入循环后第一次调用scan.nextLine()时,会直接读取这个残留的换行符,得到空字符串。这个空字符串在switch里没匹配的case,代码直接执行循环末尾的提示打印,就造成了重复输出提示的情况。
修复步骤
- 在
currentAnswer = scan.nextBoolean();之后加一行scan.nextLine();,清空缓冲区里残留的换行符。 - 调整提示信息的输出逻辑,避免重复打印:把循环末尾的提示移到条件判断里,确保只有还需要继续循环时才输出下一次提示,同时处理用户输入
false时的特殊情况。
修正后的完整代码
// 询问用户是否查看平均值 System.out.println("Do you want to view the average of your data? please answer with true or false?"); currentAnswer = scan.nextBoolean(); // 清空nextBoolean后残留的换行符 scan.nextLine(); String option; if(currentAnswer){ System.out.println("If yes, please type in one of the following(type false to exit)\n calories - protein - weight - rating"); } while(currentAnswer){ option = scan.nextLine(); switch (option) { case "calories": System.out.println(dataAverage("calories")); break; case "protein": System.out.println(dataAverage("protein")); break; case "rating": System.out.println(dataAverage("rating")); break; case "weight": System.out.println(dataAverage("weight")); break; case "false": currentAnswer = false; // 输入false时跳过后续提示打印 continue; default: // 处理无效输入 System.out.println("Invalid input, please try again."); } // 只有还在循环状态时才输出下一次提示 if(currentAnswer){ System.out.println("Please type in one of the following(type false to exit)\n calories - protein - weight - rating"); } }
额外说明
nextXxx()系列方法(除了nextLine())都不会处理输入后的换行符,用scan.nextLine()清空残留是解决这类Scanner输入问题的常用方法。- 加
default分支可以处理用户输入无效内容的情况,让程序更健壮。 - 用户输入
false时用continue跳过提示打印,避免退出前多输出一次不必要的提示。
内容的提问来源于stack exchange,提问作者Gh Fa
相关产品推荐
相关产品推荐

