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

如何移除Java数组中的0元素?(温度分类代码场景)

问题分析与解决

核心问题

你代码里的问题集中在这几点:

  • 分类数组(hot/pleasant/cold)用固定长度10,且直接使用原数组的索引i赋值,导致大量位置未被赋值(默认值为0);如果原数组长度超过10,还会触发数组越界异常。
  • 虽然统计出了各类温度的数量(H/P/C),但没有利用这些数值创建匹配长度的数组,反而用了不合理的固定长度。

解决方案(不使用ArrayList)

既然禁止使用ArrayList,我们可以分三步实现正确分类:

  1. 先遍历原数组,统计各类温度的数量(这一步你已经完成)。
  2. 用统计出的数量创建对应长度的分类数组,避免空值空间。
  3. 用独立的计数器给分类数组赋值,避免索引混乱。

修改后的完整代码

import java.util.*;

public class Array1dTemperature {
    static Scanner in = new Scanner(System.in);
    static Random rng = new Random();
    public static void main(String[] args) {
        System.out.println("This program does a temperature check.");
        System.out.println("Input the desired number of temperatures...");
        int size = in.nextInt();
        int[] temp = new int[size];
        for (int i = 0; i < temp.length; i++) {
            temp[i] = 1 + rng.nextInt(100);
        }
        System.out.println("The data file goes as: " + Arrays.toString(temp));
        Checker(temp);
    }

    static void Checker(int temp[]) {
        // 第一步:统计各类温度的数量
        int hotCount = 0, pleasantCount = 0, coldCount = 0;
        for (int t : temp) {
            if (t >= 85) {
                hotCount++;
            } else if (t >= 60 && t < 85) { // 修正原条件错误:84不应被归为cold
                pleasantCount++;
            } else {
                coldCount++;
            }
        }

        // 第二步:创建对应长度的分类数组
        int[] hot = new int[hotCount];
        int[] pleasant = new int[pleasantCount];
        int[] cold = new int[coldCount];

        // 第三步:用独立计数器赋值
        int hIdx = 0, pIdx = 0, cIdx = 0;
        for (int t : temp) {
            if (t >= 85) {
                hot[hIdx++] = t;
            } else if (t >= 60 && t < 85) {
                pleasant[pIdx++] = t;
            } else {
                cold[cIdx++] = t;
            }
        }

        // 输出无空值的结果
        System.out.println("number of hot: " + hotCount + ", Recorded temps are: " + Arrays.toString(hot));
        System.out.println("number of cold: " + coldCount + ", Recorded temps are: " + Arrays.toString(cold));
        System.out.println("number of pleasant: " + pleasantCount + ", Recorded temps are: " + Arrays.toString(pleasant));
    }
}

额外场景处理(若需移除已有数组的0元素)

如果遇到遗留的带0元素数组,可使用工具方法提取非0元素:

static int[] removeZeros(int[] arr) {
    // 先统计非0元素数量
    int nonZeroCount = 0;
    for (int num : arr) {
        if (num != 0) nonZeroCount++;
    }
    // 创建新数组并赋值
    int[] result = new int[nonZeroCount];
    int idx = 0;
    for (int num : arr) {
        if (num != 0) result[idx++] = num;
    }
    return result;
}

使用时直接调用hot = removeZeros(hot);即可,但显然从一开始就正确构建数组更高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:20:23