命令失败,线程异常,arrayindex超出范围:1

时间:2018-12-21 09:06:30

标签: java

import java.io.*;

import java.util.*;

class Mean { 

    int n, a[] = new int[n] , sum = 0, avg;

    public int getMean() { 

        Scanner in = new Scanner(System.in);
        n = in.nextInt();

        for (int i = 1; i <= n; i++) { 
            a[i] = in.nextInt();
            sum = sum + a[i];
        }

        avg = sum / n;
        return avg;
    }

    public void displayMean() {
        System.out.println(avg);
    }

}


public class TestClass {

    public static void main(String[] args) { 
        Mean obj = new Mean();
        obj.getMean();

        obj.displayMean();

    }
}

测试用例1: 5

1 3 4 5 6

预期输出: 3

1 个答案:

答案 0 :(得分:1)

读取a的值后,必须分配数组n。在您的代码中,n被初始化为0,数组a的长度为零。即使稍后更改n的值,a的长度也不会改变。

定义行变为:

int n, a[] , sum = 0, avg;

您可以这样分配:

n = in.nextInt();
a = new int[n];