有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中的indexoutofboundsexception“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();
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    静态代码在类首次加载时执行。这意味着,在main方法运行之前,您需要初始化StudentSpec。这反过来意味着n还没有赋值,所以它默认为0。因此,StudentSpec是一个维度为0乘2的数组。(请注意,不管是将代码与所有其他变量一起初始化StudentSpec,还是在类中的更高版本,所有静态内容都会首先初始化。)

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

    要解决此问题,请在读取n后在GetStudentsNumber中初始化StudentSpec,即将代码从静态初始值设定项移动到该方法