You need to enable JavaScript to run this app. Java无编译错误但输入字符串未正常输出?是否遗漏处理逻辑
优惠活动
大模型
产品
解决方案
定价
更多

Java无编译错误但输入字符串未正常输出?是否遗漏处理逻辑

问题根因

该代码不存在编译错误,空白输出是Scanner的输入读取规则导致的:

  • nextInt()、nextDouble()这类读取基本类型的方法,仅会读取匹配格式的数值内容,不会消费数值输入完成后残留的换行符(即输入数值后按回车生成的换行标记)
  • 此时直接调用nextLine(),会优先读取输入缓冲区中残留的换行符,直接返回空字符串,后续输入的实际字符串内容仍留在缓冲区未被读取,最终打印结果对应位置就是空白。
解决方法

方案一:消费残留换行符

在读取完数值类型后,先额外调用一次nextLine()清空残留的换行符,再读取实际的字符串内容。修改后代码示例:

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        double d = scan.nextDouble();
        // 清掉上一步输入数值后残留的换行符
        scan.nextLine();
        String s = scan.nextLine();
        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

方案二:统一读取整行后自行转换

如果不想额外调用nextLine(),可以统一用nextLine()读取所有输入内容,再自行转换为对应类型,适合对输入格式有更灵活控制的场景。示例代码:

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i = Integer.parseInt(scan.nextLine());
        double d = Double.parseDouble(scan.nextLine());
        String s = scan.nextLine();
        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 04:15:05