Java程序打印输入提示后无法接收用户输入如何排查解决
核心原因
你当前使用Scanner.nextLine()前,大概率之前调用过Scanner.nextInt()、Scanner.next()这类不会读取输入末尾换行符的方法,输入缓冲区残留了上一次输入留下的\n换行符,本次nextLine()直接读到了这个残留换行符,就会直接返回空字符串,看起来就像没有等待用户输入。
你贴的代码里System.out.println的内容开头带了换行属于打印格式问题,不会影响输入逻辑。
解决方案
有三种常用的修复方式,可根据你的业务场景选择:
- 方案1:额外调用
nextLine()读取残留的换行符
如果你之前确实调用过nextInt()这类方法,在调用本次读取姓名的nextLine()前,新增一行input.nextLine()吃掉残留的换行符即可:// 假设你之前有读取数值的类似代码 int studentCount = input.nextInt(); input.nextLine(); // 新增这行,清除nextInt()留下的换行符残留 System.out.println("\n\t\tAdd at least 5 members to Start the Game"); System.out.println("\n\t\tEnter Name Of Student = "); String name=input.nextLine(); - 方案2:统一使用
nextLine()读取所有输入,再做类型转换
避免混用nextInt()/next()和nextLine(),从根源解决残留换行符的问题:// 读取数值的场景改为先读字符串再转对应类型 int studentCount = Integer.parseInt(input.nextLine()); System.out.println("\n\t\tAdd at least 5 members to Start the Game"); System.out.println("\n\t\tEnter Name Of Student = "); String name=input.nextLine(); - 方案3:仅读取不含空格的姓名时,可把
nextLine()换成next()next()会自动跳过开头的所有空白字符(包括残留换行符),直到读到非空白内容为止,适合姓名不含空格的场景:System.out.println("\n\t\tAdd at least 5 members to Start the Game"); System.out.println("\n\t\tEnter Name Of Student = "); String name=input.next();
内容的提问来源于stack exchange,提问作者Zulkefal
相关产品推荐
相关产品推荐

