ArrayIndexOutofBoundException错误

时间:2016-01-19 14:02:47

标签: java arrays arraylist

我试图创建一个Java程序来计算值数组的平均值和标准差。该程序编译得很好。但是,输入arr。

的值后,我收到一个ArrayIndexOutofBoundException错误

它说错误在computeMean方法中,但我无法找到错误,因为(i

非常感谢任何帮助!

// This program computes the mean and standard deviation
// of an array of values.

import java.util.Scanner;

public class Statistics {

    public static void main(String[] args) {

        double mean, deviation; 

        int[] arr = readArray();
        arr = new int[arr.length];

        mean = computeMean(arr);
        deviation = computeStdDev(arr);

        System.out.printf("Mean = %.3f\n", mean);
        System.out.printf("Standard deviation = %.3f\n", deviation);
    }

    // Read a list of values into an array arr
    public static int[] readArray() {

        int i, size;

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter size of array: ");
        size = sc.nextInt();
        if(size == 1)
            System.out.println("Enter " + size + " value:");
        else
            System.out.println("Enter " + size + " values:");

        int[] array = new int[size];

        for(i = 0; i < size; i++)
            array[i] = sc.nextInt();

        return array;

    }

    // Compute mean of the values in arr
    // Precond: arr.length > 0
    public static double computeMean(int[] arr) {

        int i, sum = 0;

        double mean;

        for(i = 0; i < arr.length; i++);
            sum += arr[i];

        mean = sum/arr.length;

        return mean;

    }

    // Compute standard deviation of the values in arr
    // Precond: arr.length > 0
    public static double computeStdDev(int[] arr) {

        int i;
        double variance, deviation, total = 0;

        for(i = 0; i < arr.length; i++)
            total += Math.pow((arr[i] - computeMean(arr)), 2);

        variance = total/arr.length;

        deviation = Math.sqrt(variance);

        return deviation;
    }

    // Print the array arr on a single line.
    // Note that the last element has a space after it.
    public static void printArray(int[] arr) {
        for (int element: arr) {
            System.out.print(element + " ");
        }
        System.out.println();
    }
} 

1 个答案:

答案 0 :(得分:0)

在第53行;之后删除for