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

求助:Java终端降序输出数组时出现-1元素的原因

问题原因分析

为什么降序输出会出现-1?

  1. 升序阶段的处理:你在统计频率时,把数组a中重复的元素赋值为-1做标记,但升序输出时加了if (a[i] != -1)的判断,过滤掉了这些标记值,所以升序输出看不到-1。
  2. 降序阶段的问题:你直接对已经被标记了-1的数组a做降序排序,而且输出时没有过滤-1。降序排序会把-1(比所有正整数小)排到数组末尾,所以输出时这些-1就显示出来了。
  3. 额外bug:升序统计频率的代码里,if (a[i] != 1)是错误的,应该写成if (a[i] != -1)——不然如果输入中有1,会跳过对它的频率统计。
修正方案

方案1:给降序输出加过滤(快速修复)

在降序输出的循环里,同样判断a[i] != -1再打印:

System.out.println("Sorted in descending order");
System.out.println("Input	Frequency");
// 先完成降序排序
for(int i = 0 ; i < n ; i++)
{
    for(int j = i + 1 ; j < n ; j++)
    {
        if (a[i] < a[j])
        {
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
    }
}
// 排序后再过滤输出
for(int i = 0; i < n; i++){
    if(a[i] != -1){
        System.out.println(a[i] + "			"+ b[i]);
    }
}

方案2:用Map统计频率(更优雅,避免修改原数组)

用TreeMap可以直接实现升序/降序的键排序,同时统计频率,不需要手动排序和标记重复元素:

import java.util.*;

public class Q2_Frequency {
    public static void main(String[] args) {
        int sum = 0, mean;
        Scanner input = new Scanner(System.in);

        System.out.println("Please enter the number of days: ");
        int n = input.nextInt();

        int a[] = new int[n];
        System.out.println("Please enter number of trucks using a road over the " + n + " day period: ");
        for (int i = 0; i < n; i++) {
            a[i] = input.nextInt();
            sum += a[i];
        }
        mean = sum / n;
        System.out.println("The mean is: " + mean);

        // 用TreeMap统计频率,默认升序
        TreeMap<Integer, Integer> freqMap = new TreeMap<>();
        for(int num : a){
            freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
        }

        // 升序输出
        System.out.println("Sorted in ascending order");
        System.out.println("Input	Frequency");
        for(Map.Entry<Integer, Integer> entry : freqMap.entrySet()){
            System.out.println(entry.getKey() + "			" + entry.getValue());
        }

        // 降序输出,用TreeMap的descendingMap()
        System.out.println("Sorted in descending order");
        System.out.println("Input	Frequency");
        for(Map.Entry<Integer, Integer> entry : freqMap.descendingMap().entrySet()){
            System.out.println(entry.getKey() + "			" + entry.getValue());
        }

        System.out.println("Number of input is: " + a.length);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:45:33