Java 1.4.2 - ArrayIndexOutOfBounds错误

时间:2013-08-07 15:07:21

标签: java indexoutofboundsexception

(我正在使用Java 1.4.2)我希望有一个数组应该在用户给出的一定时间内翻转“硬币”(硬币可以翻转1000次)。然后随机生成1到10之间的整数,将所有数字存储在数组中。我有以下代码,但它一直给我以下错误:

  

线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:7   在CoinFlip.main(CoinFlip.java:42)

这是我写的代码。

import java.io.*;
import java.math.*;

public class CoinFlip
{
    public static void main(String[] args) throws IOException
    {
        // setting up variables
        String timesString;
        int times;
        // setting up input
        BufferedReader in;
        in = new BufferedReader(new InputStreamReader(System.in));


        do
        {
            // times will display how many times the coin will flip
            // loop if times does not fulfill the requirements
            System.out.println("How many times do you want the coin to flip? (MUST be an integer between 1 to 1000)");
            timesString = in.readLine();
            // convert timesString into an integer
            times = Integer.valueOf(timesString).intValue();
            if((times > 1000)||(times < 1))
            {
                System.out.println("ERROR: The number of times you flip the coin must be an integer between 1 and 1000.");
            }
            System.out.println("The value for times is " +times);
        }
        while((times > 1000)||(times < 1));


        // create a new array
        double flip[] = new double[times];

        // create a new variable timeStore that sets the boolean conditions for the For Loop
        int timeStore;
        for(timeStore = 0; timeStore <= times-1; timeStore++)
        {
            System.out.println("timeStore (how many iterations) is " +timeStore);
            System.out.println("FOR LOOP:  When " +timeStore+ " is less than or equal to " +(times-1));
            flip[times] = Math.round(Math.random()*9)+1;
            // the line above stores a random integer between 1 and 10 within the current index
            System.out.println("flip["+times+"] = "+flip[times]);
        }

    }
}

2 个答案:

答案 0 :(得分:5)

第42行;

flip[times] = Math.round(Math.random()*9)+1;

应该是;

flip[timeStore] = Math.round(Math.random()*9)+1;

然后也在第44行的System.out中。

答案 1 :(得分:2)

这些都是错的:

42: flip[times] = Math.round(Math. random()* 9 ) + 1;
44: System.out.println("flip[" + times + "] = " + flip[times]);

看来你的意思是

42: flip[timeStore] = Math.round(Math.random()*9)+1;
44: System.out.println("flip["+timeStore+"] = "+flip[timeStore]);

由于您将flip声明为大小为times的数组,因此只有索引0...(times - 1)才有效。特别是,索引times无效,因此flip[times]会抛出。

请注意,编译器告诉您有问题的行,并且传入了违规索引。它告诉您传入7作为索引。但请注意,此异常发生在循环的第一次迭代中。您可以通过代码中的有用打印调试语句生成程序产生的输出来判断。因此,您应该可以推断:嘿,当索引应该为0时,为什么我的数组在循环的第一次迭代中看到索引7?此时,错误实际上已经形成了自己。

此外,数组的惯用用法是:

for(timeStore = 0; timeStore < times; timeStore++)

甚至更好的是:

for(timeStore = 0; timeStore < flip.length; timeStore++)