【发布时间】: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