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

Java代码运行报Standard Output is Empty错误,请求帮忙排查

问题排查及修复方案

错误根因

  • 同时使用Scanner和BufferedReader读取同一输入流System.in是核心问题:Scanner.nextInt()只会读取输入中的数字内容,不会消费数字后的换行符,该换行符会直接残留在输入缓冲区中
  • 后续BufferedReader.readLine()执行时,会优先读取到缓冲区残留的换行符,再加上你给出的输入中5后还有一行空行,最终readLine()拿到的是空字符串,调用split(" ")后得到的数组长度不符合预期,程序抛出数组越界异常直接终止,没有生成任何标准输出,因此触发了对应报错。

修复方案

不要混用两种输入读取类,统一用其中一种即可,以下是两种可行的修复实现:

方案1:全用Scanner实现(写法更简洁)

import java.util.*;
public class CandidateCode {
    public static void main(String args[] ) throws Exception {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int[] arr = new int[n];
        int tot = 1;
        for(int i = 0; i < n; i++){
            arr[i] = s.nextInt();
        }
        for(int num : arr){
            tot *= num;
        }
        System.out.println(tot);
    }
}

方案2:全用BufferedReader实现(读取大输入性能更高)

import java.io.*;
public class CandidateCode {
    public static void main(String args[] ) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine().trim());
        // 兼容输入中可能存在的空行
        String line;
        while((line = br.readLine()) != null && line.trim().isEmpty());
        String[] strs = line.trim().split(" ");
        int[] arr = new int[n];
        int tot = 1;
        for(int i = 0; i < n; i++){
            arr[i] = Integer.parseInt(strs[i]);
        }
        for(int num : arr){
            tot *= num;
        }
        System.out.println(tot);
    }
}

验证结果

针对你给出的输入5、空行、1 2 3 4 5,两种修复后的代码都会正常输出计算结果120,不会出现无输出的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:24:03