nextline()“跳过”输入是因nextint()等方法残留换行符;解决方法是在nextxxx()后加sc.nextline()清空缓冲区,或统一用nextline()配合integer.parseint()等转换。

用 Scanner.nextLine() 读取带空格的输入本身没问题,真正容易出问题的是它和 nextXXX() 方法(比如 nextInt()、nextDouble())混用时留下的换行符残留。
为什么 nextLine() 会“跳过”输入?
这是因为 nextInt() 等方法只读取数字,不消费输入末尾的回车(\n)。紧接着调用 nextLine(),它立刻读到这个残留的换行符,返回一个空字符串,看起来就像“跳过了”输入。
例如:
Scanner sc = new Scanner(System.in);
System.out.print("年龄:");
int age = sc.nextInt(); // 输入 25 回车 → 缓冲区剩下 \n
System.out.print("姓名:");
String name = sc.nextLine(); // 立刻读到 \n → name 是 ""
标准解决办法:加一句 nextLine() 清空缓冲区
在每个 nextXXX() 后,手动加一次 sc.nextLine() 吃掉换行符:
-
先读数字:用
nextInt()或nextDouble() -
再清空:立即调用一次
sc.nextLine() -
最后读字符串:再用
nextLine()读带空格的内容
Scanner sc = new Scanner(System.in);
System.out.print("年龄:");
int age = sc.nextInt();
sc.nextLine(); // ← 关键:吃掉换行符
System.out.print("姓名:");
String name = sc.nextLine(); // 这次能正常读 "张 三" 了
更稳妥的做法:统一用 nextLine() + 类型转换
完全避免混用,所有输入都用 nextLine(),再手动转类型:
- 读整数:
int age = Integer.parseInt(sc.nextLine().trim()); - 读浮点数:
double price = Double.parseDouble(sc.nextLine().trim()); - 读字符串:
String address = sc.nextLine(); -
trim()可防用户多输空格,提升健壮性
注意 nextLine() 本身的特性
它以整个行(直到回车)为单位读取,天然支持空格、制表符、中文等任意字符,不会截断。唯一要注意的是:
- 如果用户直接按回车,
nextLine()返回空字符串"",不是null - 需要判空时用
str.isEmpty()或str.trim().isEmpty() - 不要用
==判断字符串内容,要用.equals()










