ArrayIndexOutOfBoundsException在Simon Game中,无法弄清楚为什么

时间:2012-11-18 20:44:19

标签: input

我对Java很新,但一般不是OOP。我正在研究经典的Simon游戏,其中用户遵循我的Java类随机生成的模式(数字真的)的增加序列。我收到了一个错误:

java.lang.ArrayIndexOutOfBoundsException: 20
at Simon.generateSequence(Simon.java:58)
at Simon.<init>(Simon.java:23)

我无法弄清楚如何解决这个问题。它看起来不像我调用的元素多于数组中的元素。这是代码:

import acm.program.*;
import acm.graphics.*;
import java.awt.Color;
import java.awt.Font;
import javax.swing.*;
import java.awt.event.*;


public class Simon extends Program implements ActionListener
{
private int array[];
private int currentSeqLength;
private int usersInput;


public Simon()
{
    //Initialize Class Values
    array = new int[20];
    currentSeqLength = 1;
    usersInput = 0;

    generateSequence();

    while(currentSeqLength <= array.length)
    {
        playSequence();

        //Wait For User's Input Here, Assign To Variable
        //usersInput = 

        if (pushButton(usersInput)== true)
        {

            currentSeqLength++;
        }

        else
        {
            gameOverMessage();
            break;

            //Reset Variables:

        }

    }


}

public void generateSequence()
{

    //Fill Array With Random Numbers
    for (int i = 0; i <= array.length; i++ )
    {
        array[i] = (int)(Math.random()*4);

    }


}

public void setLength(int length)
{
    //Set Current Length To Size Of Given Argument
    currentSeqLength = length;

}

int getLength()
{
    return currentSeqLength;

}

int[] playSequence()
{
    //Print Out The Current Sequence

    //New Local Array To Return
    int newArray[]= new int[currentSeqLength];


    //Repeat As Many Times As Value Of currentSeqLength
    for(int i = 0; i <= currentSeqLength ; i++)
    {
        System.out.println(array[i]);

        //Return an array of int's to the player. 
        newArray[i] = array[i];

    }

    return newArray;
}

boolean pushButton(int usersInput)
{
    //Given A Button Press (0-3), Return Whether That Was The 
        //Correct Button To Play At The Moment

    if (usersInput == array[currentSeqLength])
    {
        return true;
    }

    else
    {
        return false;
    }


}

boolean isTurnOver()
{
    //If Current Sequence Length Matches Or Exceeds Value Of 
        //Array Element In Location Of Current Sequence Length

    if (currentSeqLength >= array[currentSeqLength])
    {
        return true;
    }

    else
    {
        return false;
    }

}

//Not Needed?
boolean isGameOver()
{
    if (pushButton(usersInput) == false)
    {
        return true;
    }

    else
    {
        return false;
    }
}

String gameOverMessage()
{
    return "Game Over";
}

/*public void actionPerformed(ActionEvent event)
{
    int input;


}
*/

}

1 个答案:

答案 0 :(得分:0)

for (int i = 0; i <= array.length; i++ )
    {
        array[i] = (int)(Math.random()*4);

    }

你从0到20循环.20是数组的长度,21是for循环的迭代次数。

用&lt;。

替换&lt; =