简体   繁体   English

如何解决Java越界编码错误?

[英]How to resolve Java out of bounds coding error?

I am trying to create a Times Tables quiz on BlueJ using Java and every time I try and run this code it tells me that there is an out of bounds exception and highlights the starred line of code. 我正在尝试使用Java在BlueJ上创建一个Times Tables测验,每次尝试运行此代码时,它都告诉我存在一个超出范围的异常,并突出显示了加星号的代码行。

public void getQuestion()
{
    boolean newQuestion;

    Random randomGenerator = new Random();
    int randomInt = 0;
    for (int j=1; j<=12; j++)
    {
        newQuestion=false;
        int i=0;
        while (newQuestion==false)
        {
            randomInt = randomGenerator.nextInt(12);
            randomInt = randomInt + 1;
            while ((chosenArray [i]!=randomInt) && (chosenArray[i]!= randomInt))
            {
                i=i+1;
                ***if (chosenArray[i]==0)***
                {
                    newQuestion = true;
                    chosenArray[i]=randomInt;

                }

            }

        }

    }
    System.out.print(timesTableChosen + " x " + randomInt + " = "); 
}

} }

How should I resolve this so that it works? 我应该如何解决才能使其正常工作? Thanks. 谢谢。

The root cause is that you overindex when increasing i , Use modulo operator % : 根本原因是增加i时索引过度,请使用模运算符%

i=(i+1) % 12;

BTW, instead of magic numbers, like 12 , I'd use chosenArray.length , always. 顺便说一句,而不是像12这样的魔术数字,我总是使用chosenArray.length

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM