我无法弄清楚的ArrayIndexOutOfBoundsException异常

时间:2015-10-12 00:04:14

标签: java arrays indexing

我只是想弄清楚为什么我一直得到一个indexoutofboundserror。我相信它会突然出现

profits[i] = storeDays

代码是:

import java.util.Arrays;
import java.util.Scanner;

class Business
{
    public static void main(String[] args) {
        Scanner inputScanner;
        inputScanner = new Scanner (System.in);
        System.out.println("Welcome to the profit-calculation program.");
        System.out.println("how many days of data do you have?");
        int n = Integer.parseInt (inputScanner.nextLine());

    //call upon a function to store the profits into an array for further     use.
        double[] dayProfitList = inputProfit(n);
    //call upon a function to calculate average profit and its standard devation

    //calcAverageProfit(dayProfitList);


    }

        public static double[] inputProfit(int days) {
            Scanner inputScanner;
            inputScanner = new Scanner (System.in);

            System.out.println("input the profit on..");
            double[] profits = new double [days];

            for(int i = 1; i<days +1; i++) {
                System.out.println("day " + i + "?");
                double storedDays = Double.parseDouble(inputScan ner.nextLine());
                profits[i] = storedDays;
            }
            return profits;
    }
}

1 个答案:

答案 0 :(得分:1)

阵列来自 0 ,所以它的第一个元素是利润[0] ,下一个是利润[1] 等等上。

您正尝试访问此处不存在的索引:

for(int i = 1; i<days +1; i++) {
    ...

实际应该是

for(int i = 0; i<days; i++) {
    ...