Java do-while循环未满足判断条件时程序提前退出问题排查
问题根本原因
do-while循环提前退出、无法接收用户输入的核心原因是重复创建了绑定System.in的独立Scanner对象:
你在do-while循环外部创建了一个Scanner对象用于读取Y/N选择,又在UserAddedExercise()方法内部创建了第二个绑定同一个标准输入流的局部Scanner。两个独立Scanner各自维护独立的输入缓冲区,方法内部的Scanner读取完4项训练信息后,会意外消费掉输入流里残留的换行符,甚至把外层Scanner待读取的输入内容提前吞入自己的缓冲区。等方法执行结束,局部Scanner被回收,外层Scanner调用nextLine()时会直接读取到空值/空字符串,不会阻塞等待用户输入,空字符串和"y"做等值判断必然返回false,循环就直接终止了。
修复方案
- 全局只保留一个绑定
System.in的Scanner实例,禁止在输入方法内部重复new Scanner(System.in)。可以把Scanner定义为类的静态成员,供所有需要读取输入的方法共用,从根源避免多Scanner抢占同一输入流导致的缓冲区错位、数据丢失问题。 - 调整
UserAddedExercise()方法的返回值,把方法内创建好的Exercise对象直接返回,方便后续存入ArrayList集合,不需要额外做对象的中转获取。
修复后的核心代码如下:
主循环逻辑
import java.util.ArrayList; import java.util.Scanner; public class ExerciseManager { // 全局唯一的Scanner实例,所有输入逻辑共用 private static final Scanner in = new Scanner(System.in); // 存储所有Exercise对象的ArrayList private static final ArrayList<Exercise> exerciseSet = new ArrayList<>(); public static void main(String[] args) { String s; do { // 拿到创建好的训练动作对象,直接存入集合 Exercise newExercise = UserAddedExercise(); exerciseSet.add(newExercise); System.out.print("Do you want to add another exercise? (Y/N) "); s = in.nextLine(); } while (s.equalsIgnoreCase("y")); // 所有输入完成后再关闭Scanner,不要中途关闭 in.close(); // 后续可以添加打印exerciseSet、持久化存储等逻辑 } }
调整后的输入方法
public static Exercise UserAddedExercise() { // 不再重复创建Scanner,直接使用全局共用的in实例 System.out.print("Enter the exercise name: "); String exe = in.nextLine(); System.out.print("Enter the location for the exercise: "); String loc = in.nextLine(); System.out.print("Enter if the exercise is weighted or not: "); String w = in.nextLine(); System.out.print("Enter the the muscle location exercised: "); String ml = in.nextLine(); // 返回创建完成的Exercise对象 return new Exercise(exe, loc, w, ml); }
你提供的Exercise类实现没有逻辑问题,不需要做任何修改即可正常使用。
内容的提问来源于stack exchange,提问作者Lofton Gentry
相关产品推荐
相关产品推荐

