【问题标题】:I keep getting java.lang.ArrayIndexOutOfBoundsException: 5! How do I fix this? [closed]我不断收到 java.lang.ArrayIndexOutOfBoundsException: 5!我该如何解决? [关闭]
【发布时间】:2013-10-15 18:09:53
【问题描述】:

我不断收到错误代码:java.lang.ArrayIndexOutOfBoundsException: 5 或使用随机数而不是 5。我正在尝试编写一个脚本,该脚本从用户输入中获取测试分数列表,然后计算他们的最高分数输入。我该如何解决这个问题?

注意:“scores”是我的数组列表名称,“testNum”是他们输入的测试分数。

System.out.print ("Enter a set of test scores, hitting enter after each one: ");
//---------------------------------------------------------------------------------------
//   loop that will set values to the scores array until the user's set amount is reached.
//---------------------------------------------------------------------------------------
for(int x = 0; x < testNum; x += 1) //x will approach testNum until it is less than it, then stop.
{
    scores[x] = scan.nextInt();

} //working



    for(int z = 0, a = 1; z < testNum; z += 1) // attempts to find the highest number entered.
{
    if (scores[z] > scores[z + a])
    {
        a += 1;
        z -= 1; //offsets the loop's += 1 to keep the same value of z
    }
    else
    {
        if (z + a >= testNum)
        {
            System.out.println ("The highest number  was " + scores[z]);
        }
        a = 0; //resets a to try another value of scores[z].

    }
}

【问题讨论】:

  • scores 的大小是多少?
  • 停止尝试访问数组元素5
  • 你的标题很有欺骗性......我建议你问类似'如何在 javascript 中迭代数组'

标签: java arrays if-statement for-loop runtime-error


【解决方案1】:

根据您所展示的内容:

testNum 大于 scores.length。这意味着当您通过将迭代器 (i) 与 testNum 进行比较而不是其实际长度来遍历数组时,您将遇到不存在的索引。

例如,假设testNum = 8scores.length = 5。然后在您的代码中,您将得到一个ArrayIndexOutOfBoundsException:5,因为您的循环遍历索引 0、1、2、3 和 4(请记住,数组从索引 0 开始)然后尝试访问超出范围的 5(如例外说)。

您可以使用以下任一技术正确遍历数组,具体取决于您的用例:

for(int i = 0; i < scores.length; i++) {
    //do stuff
}

...或...

for(int score : scores) {
    //do stuff
}

【讨论】:

    猜你喜欢
    • 2013-03-19
    • 1970-01-01
    • 2019-09-16
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 2019-11-24
    • 2015-03-23
    相关资源
    最近更新 更多