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

Java中Scanner对象在方法中被无理由跳过且无报错,求原因

Scanner的nextInt()后nextLine()被跳过的问题分析与解决

问题原因

input.nextInt()方法仅读取输入中的数字字符,不会处理输入末尾的换行符(即按下回车键产生的\n)。当你输入账号并回车后,这个换行符会残留在输入缓冲区中。后续调用input.nextLine()时,它会直接读取这个残留的换行符,将其视为一次完整的输入,因此跳过了用户输入账户持有人姓名的步骤。

解决方案

有两种可靠的解决方式:

方式一:用额外的nextLine()消耗残留换行符

在nextInt()执行后,添加一个空的input.nextLine()来清空缓冲区里的换行符:

public void createNewAccount() {
    System.out.println("Enter account number: ");
    account.setAccountNumber(input.nextInt());
    input.nextLine(); // 消耗掉账号输入后的换行符
    
    System.out.println("Enter account holder: ");
    account.setHolderName(input.nextLine());
    
    // 后续代码保持不变
    System.out.println("There is a initial deposit? (y/n)");
    String initialDepositOption = input.nextLine();
    
    if(initialDepositOption.equalsIgnoreCase("y")) {
        System.out.println("Enter the initial deposit value: ");
        account.setAmount(input.nextDouble());
        input.nextLine(); // 如果后续还有nextLine(),这里也需要添加
    }
    
    System.out.println(toString());
}

注意:如果后续还有nextDouble()这类不处理换行符的方法,之后的nextLine()前也需要加同样的处理。

方式二:统一用nextLine()读取所有输入,再转换类型

放弃使用nextInt()、nextDouble(),全部用nextLine()读取输入字符串,再手动转换成对应类型,这种方式更统一,还能避免输入非法格式时的异常:

public void createNewAccount() {
    System.out.println("Enter account number: ");
    try {
        int accountNum = Integer.parseInt(input.nextLine());
        account.setAccountNumber(accountNum);
    } catch (NumberFormatException e) {
        System.out.println("请输入有效的数字账号");
        return; // 或者做其他异常处理
    }
    
    System.out.println("Enter account holder: ");
    account.setHolderName(input.nextLine());
    
    System.out.println("There is a initial deposit? (y/n)");
    String initialDepositOption = input.nextLine();
    
    if(initialDepositOption.equalsIgnoreCase("y")) {
        System.out.println("Enter the initial deposit value: ");
        try {
            double deposit = Double.parseDouble(input.nextLine());
            account.setAmount(deposit);
        } catch (NumberFormatException e) {
            System.out.println("请输入有效的金额");
        }
    }
    
    System.out.println(toString());
}

关于你之前尝试的说明

  • 关闭Scanner后重建报错:因为System.in是一个全局的标准输入流,一旦关闭就无法再次打开,所以不能随便关闭Scanner实例。
  • 添加空println()无效:这种操作不会改变输入缓冲区的内容,自然无法解决残留换行符的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:25:22