【问题标题】:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException [duplicate]线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException [重复]
【发布时间】:2011-07-07 18:40:02
【问题描述】:

我是编程新手,在 Eclipse 中运行一些新代码时遇到了这个错误,完全迷失了。

import java.util.Scanner;

public class Lab6
{
    public static void main(String[] args)
    {
        // Fill in the body according to the following comments
    Scanner in= new Scanner(System.in); 
        // Input file name
        String FileName=getFileName(in);
        // Input number of students
        int numOfStudents = FileIOHelper.getNumberOfStudents(FileName);
        Student students[] = getStudents(numOfStudents); 
        // Input all student records and create Student array and
        // integer array for total scores
        int[]totalScores = new int[students.length];
        for(int i=0; i< students.length; i++)
        {
            for(int j=1; j<4; j++)
            {
                totalScores[i]= totalScores[i]+students[i].getScore(j);
            }
        }
        // Compute total scores and find students with lowest and
        // highest total score
        int i;
        int maxIndex =0;
        int minIndex =0;
        for(i=0; i<students.length; i++);
        {
            if(totalScores[i]>=totalScores[maxIndex])
            {
                maxIndex=i;
            }
            else if(totalScores[i]<=totalScores[minIndex])
            {
                minIndex=i;
            }
        }

问题似乎在 if(totalScores[i]>=totalScores[maxIndex])

【问题讨论】:

  • 堆栈跟踪的前几行(从您的 ArrayIndexOutOfBoundsException 开始)很关键。
  • 代码中的另一个错误是 ;在 for() 之后。

标签: java arrays exception


【解决方案1】:

您在最后一个for 之后有一个;,因此在for 执行之后,每个步骤中都没有其他命令,变量i 将具有值students.length,它超出了大批。然后,for 后面的 { ... } 块以 i 的最终值执行一次,导致异常。

删除;,它应该可以工作。

【讨论】:

    【解决方案2】:

    这行有问题

    int[]totalScores = new int[students.length];

    for(int i=0;i

    您为总分分配了students.length 大小.. 但您使用的是4*students.length.. 所以arrayindex 超出范围。用这个

    int[]totalScores = new int[4*students.length];

    谢谢 是的

    【讨论】:

    • 这不是问题,他从不访问像totalScores[i*j] 这样的东西,只访问totalScores[i](和students[i]),所以大小合适。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多