Java Scanner的nextLine()读取空行问题及循环终止需求求助
问题分析与解决方案
你的代码出现首次循环后nextLine()读取空行的问题,核心原因是混合使用next()和nextLine()导致输入流残留换行符:
sc.next()只会读取到Y/N这类非空白字符串,输入时按下的回车键(换行符)会留在输入缓冲区中;- 下一次循环执行
sc.nextLine()时,会直接读取这个残留的换行符,得到空字符串,进而引发后续逻辑错误。
同时要确保输入非"Y"时终止循环,下面给出两种可靠的修复方案:
方案一:清空next()后的残留换行符
在调用sc.next()读取选择后,额外调用一次sc.nextLine()清空缓冲区里的换行符,避免影响下一次nextLine()的读取:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); do { System.out.println("write in format \"firstname lastname\""); String[] tempArr = sc.nextLine().split(" "); System.out.println("Hello " + tempArr[0]); System.out.println("Do you want to do it again Y/N"); // 读取选择并清空换行符 String choice = sc.next(); sc.nextLine(); }while(choice.equals("Y")); sc.close(); } }
方案二:统一使用nextLine()处理所有输入(推荐)
避免混合使用不同的Scanner读取方法,统一用nextLine()读取所有输入,同时可以优化输入的健壮性(比如兼容小写y、处理输入前后空格):
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String choice; do { System.out.println("write in format \"firstname lastname\""); // 先trim去掉首尾空格,再用\\s+分割任意空白字符,避免多空格导致空数组元素 String[] tempArr = sc.nextLine().trim().split("\\s+"); System.out.println("Hello " + tempArr[0]); System.out.println("Do you want to do it again Y/N"); // 读取选择并去除前后空格 choice = sc.nextLine().trim(); }while(choice.equalsIgnoreCase("Y")); // 兼容Y/y两种输入 sc.close(); } }
额外优化提示
如果用户输入多个空格分隔名字,split(" ")会生成包含空字符串的数组,用split("\\s+")可以匹配任意数量的空白字符(空格、制表符等),配合trim()去掉首尾空格,能让输入处理更健壮。
内容的提问来源于stack exchange,提问作者Vikki
相关产品推荐
相关产品推荐

