首页 > 解决方案 > Java 中的“java.lang.ArrayIndexOutOfBoundsException”错误

问题描述

我正在编写一个简单的 Java 代码,输入第一个输入后出现此错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at university.GetStudentSpect(university.java:26)
at university.main(university.java:11)

代码:

import java.util.Scanner;
public class university {
    public static Scanner Reader = new Scanner(System.in);
    public static int n;
    public static int m=0;
    public static int l;
    public static StringBuilder SConverter = new StringBuilder();
    public static void main(String[] args) {
        GetStudentsNumber();
        GetStudentSpect();
    }

    public static void GetStudentsNumber() {
        System.out.println("enter the number of students");
        n = Reader.nextInt();
    }
    public static String [][] StudentSpect = new String [n][2];

    public static void GetStudentSpect() {
        for (int i=0;i<n;i++) {
            System.out.println("enter the name of the student");
            StudentSpect[i][0] = SConverter.append(Reader.nextInt()).toString();
            System.out.println("enter the id of the student");
            StudentSpect[i][1] = SConverter.append(Reader.nextInt()).toString();
            System.out.println("enter the number of courses of the student");
            l = Reader.nextInt();
            m += l;
            StudentSpect[i][2] = SConverter.append(l).toString();
        }
    }
}

标签: javaindexoutofboundsexception

解决方案


首次加载类时会执行静态代码。这意味着,您在方法运行StudentSpec之前进行初始化。main这反过来意味着n尚未分配值,因此它默认为 0。因此,它StudentSpec是一个维度为零乘二的数组。(请注意,无论您是将代码StudentSpec与所有其他变量一起初始化还是稍后在类中初始化,所有静态内容都会首先初始化。)

然后你的代码main运行,调用GetStudentsNumber,它设置n,但不初始化StudentSpec(再次)。然后GetStudentSpect运行,一旦你尝试访问StudentSpec,你的程序就会崩溃,因为它是一个元素为零的数组。

要解决此问题,请StudentSpecGetStudentsNumber读取后n初始化,即将代码从静态初始化程序移动到此方法。


推荐阅读