2013-10-08 32 views
-5

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

注:“成绩”是我的数组列表名称和“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]. 

    } 
} 
+2

什么'scores'的大小? –

+1

停止尝试访问数组元素'5'。 – asteri

+0

你的标题是非常具有欺骗性的......我会建议问'我如何在javascript中迭代数组' – DigitalJedi805

回答

0

testNum较大比scores.length。这意味着当你通过比较你的迭代器(i)到testNum而不是它的实际长度来遍历数组时,你会碰到不存在的索引。例如,假设testNum = 8scores.length = 5。然后在你的代码中,你会得到一个ArrayIndexOutOfBoundsException:5,因为你的循环遍历索引0,1,2,3和4(记住数组从索引0开始),然后尝试访问5,这是超出界限的(作为Exception说的)。

您可以使用以下方法正确遍历数组,这取决于你的使用情况:

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

......或者......

for(int score : scores) { 
    //do stuff 
} 
相关问题