为什么我会收到“Out of Bounds”错误?

时间:2013-04-27 02:39:42

标签: java indexoutofboundsexception

当我使用此编码来获取用户输入时,我发现了一个没有键错误。 noOfJudges的用户输入是数组的长度。对于每个裁判,输入并测试分数以查看它是否在1到10之间 代码:

  double [] scores = new double [noOfJudges];

  System.out.print("Please enter the next score: ");
  for(scoreEntry = 0; scoreEntry < scores.length; scoreEntry++)
      scores[scoreEntry]=console.nextDouble();
  System.out.println();


      while((scores[scoreEntry] < MIN_SCORE)||(scores[scoreEntry] > MAX_SCORE))
      {
         System.out.print("Please reenter the score (must be between 1.0 and 10.0, in .5 increments): ");
         scores[scoreEntry] = console.nextDouble();
         System.out.println();
      }

如果有人想要完美,有没有办法检查一个数字是否在1到10之间,并且只有.5增量?

3 个答案:

答案 0 :(得分:0)

您应该使用局部变量来 for循环或重置scoreEntry,因为在 for循环的末尾 scoreEntry是相等的到数组的长度,这不是一个有效的索引......

答案 1 :(得分:0)

for循环结束后,

执行System.out.println(scoreEntry);

你的答案就在于:)

最佳,

ANKIT

答案 2 :(得分:0)

您必须忘记一对{}

double[] scores = new double[noOfJudges];

System.out.print("Please enter the next score: ");
for(scoreEntry = 0; scoreEntry < scores.length; scoreEntry++) {
    scores[scoreEntry] = console.nextDouble();
    System.out.println();
    while((scores[scoreEntry] < MIN_SCORE) || (scores[scoreEntry] > MAX_SCORE)){
        System.out.print("Please reenter the score " + 
            "(must be between 1.0 and 10.0, in .5 increments): ");
        scores[scoreEntry] = console.nextDouble();
        System.out.println();
    }
}