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

Java程序输出末尾出现多余0问题求助:输入4时多一行0

问题分析与解决方案

你的代码在输入k=4时末尾多出一个0,核心原因是代码末尾存在一段多余的输出逻辑,这段逻辑会在完成k-1个分位数输出后,额外输出一个值,而这个值恰好是0(可能源于你的数据中存在0,或队列处理后的异常结果)。

具体问题点

当k=4时,你需要输出3个四分位数,代码中的for (int j = 1; j < k; j++)循环已经执行3次,正确输出了3个分位数。但循环结束后,你又执行了以下完全超出需求的逻辑:

  1. 将剩余元素加入优先队列
  2. 清空队列至只剩一个元素
  3. 输出该元素

这段冗余逻辑直接导致多输出了一行内容。

修改方案

直接删除以下多余代码块:

while (i < n) {
    pq.offer(-list.get(i));
    i++;
}

while (pq.size() > 1) {
    pq.poll();
}

System.out.println(-pq.peek());

修改后的完整代码

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;

public class Quantiles {
    public static void main(String[] args) {
        int k = 0;
        Scanner scanner = new Scanner(System.in);
        System.out.print("");
        k = scanner.nextInt();

        ArrayList<Integer> list = new ArrayList<Integer>();

        try {
            Scanner sc = new Scanner(new File("Incomes.txt"));
            while (sc.hasNextLine()) {
                list.add(Integer.parseInt(sc.nextLine()));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        Collections.sort(list);

        int n = list.size();
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        int i = 0;
        for (int j = 1; j < k; j++) {
            int nextIndex = j * n / k;
            while (i < nextIndex) {
                pq.offer(-list.get(i));
                i++;
            }
            System.out.println(-pq.peek());
        }
    }
}

补充说明

如果你的分位数计算逻辑还有精度问题(比如当n无法被k整除时的分位数取值),可以进一步调整nextIndex的计算方式(例如使用向上取整),但当前核心问题已通过删除冗余逻辑解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:24:59