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

Java一维数组计算代码出现数组越界异常求助

问题分析与修复

数组越界的直接原因

在main方法的输入循环结束后,变量x的值等于N(因为循环条件是x < N,当x递增到N时才会退出循环)。而数组arr的下标范围是0到N-1,调用AVER(arr, average, count_negative_elements, N, x)时传入x=N,在AVER方法里执行sum += arr[x]就会触发IndexOutOfBoundsException。

额外逻辑问题

你的AVER方法根本没遍历数组,只处理了单个元素,完全达不到计算平均值和统计负数的目的:

  • 计算平均值时只累加了arr[x],不是所有元素的总和
  • 统计负数时只检查了当前arr[x],没有遍历整个数组计数和收集所有负数

修复后的代码

package myMethods;

import java.util.Scanner;

public class CalculationsOnArrays {

    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);

        System.out.println("How many numbers are in the array");
        int N = input.nextInt();
        int[] arr = new int[N];

        System.out.println("Enter the numbers");
        for (int x = 0; x < N; x++) {
            arr[x] = input.nextInt();
        }

        // 调用修复后的方法
        calculateArrayStats(arr);

        input.close();
    }

    static void calculateArrayStats(int[] arr) {
        int sum = 0;
        int negativeCount = 0;
        StringBuilder negativeNumbers = new StringBuilder();

        // 遍历数组计算总和与统计负数
        for (int num : arr) {
            sum += num;
            if (num < 0) {
                negativeCount++;
                if (negativeNumbers.length() > 0) {
                    negativeNumbers.append(", ");
                }
                negativeNumbers.append(num);
            }
        }

        // 计算平均值(转成double避免整数除法精度丢失)
        double average = (double) sum / arr.length;
        System.out.println("The average of the numbers is " + average);

        // 输出负数统计结果
        System.out.println("The negative numbers in the array are " + negativeCount);
        if (negativeCount > 0) {
            System.out.println("They are " + negativeNumbers);
        } else {
            System.out.println("There are no negative numbers.");
        }
    }
}

修复点说明

  • 移除了不必要的参数传递,直接传入数组,彻底避免了变量x带来的越界问题
  • 用增强for循环遍历整个数组,确保每个元素都被处理
  • 计算平均值时将sum转为double,避免整数除法导致的精度丢失
  • 用StringBuilder收集所有负数,输出结果更清晰
  • 优化了变量命名,提升代码可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:35:20