You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Scanner调用nextInt()后nextLine()被跳过的问题求助

Scanner类nextInt()后nextLine()被跳过的问题解决

问题原因

nextInt()仅读取输入中的整数内容,当你输入整数后按下回车,输入缓冲区会残留一个换行符(\n)。后续调用nextLine()时,它会直接读取这个换行符作为空字符串,导致程序跳过了姓名输入步骤。

解决方案

方法1:额外调用nextLine()清空缓冲区

在nextInt()之后添加一行sc.nextLine(),专门消耗掉残留的换行符:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your age: ");
        int age = sc.nextInt();
        sc.nextLine(); // 清除缓冲区里的换行符
        System.out.print("Enter your name: ");
        String name = sc.nextLine();
        System.out.println("Name: " + name + ", Age: " + age);
    }
}

方法2:用nextLine()读取后转整数

全程使用nextLine()读取输入,再将年龄的字符串转换为整数,从根源避免换行符残留:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your age: ");
        // 读取整行输入再转换为整数
        int age = Integer.parseInt(sc.nextLine());
        System.out.print("Enter your name: ");
        String name = sc.nextLine();
        System.out.println("Name: " + name + ", Age: " + age);
    }
}

注意:如果输入的不是有效整数,会抛出NumberFormatException,可以添加try-catch块处理异常,提升程序健壮性。

方法3:用next()读取姓名(限无空格姓名)

如果姓名输入不含空格,可使用next()替代nextLine()——next()会自动跳过所有前置空白字符(包括换行符),直到读取到有效字符:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your age: ");
        int age = sc.nextInt();
        System.out.print("Enter your name: ");
        String name = sc.next(); // 仅能读取无空格的字符串
        System.out.println("Name: " + name + ", Age: " + age);
    }
}

局限性:无法读取包含空格的姓名(如"Mary Ann")。

内容的提问来源于stack exchange,提问作者Leonardo_GT2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.02 05:54:52