Java

时间:2019-03-01 14:01:58

标签: java indexoutofboundsexception

我正在编写一个简单的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();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

首次加载该类时,将执行静态代码。也就是说,您需要在StudentSpec方法运行之前初始化main。相应地,这意味着n尚未分配值,因此它默认为0。因此,StudentSpec是尺寸为零乘以2的数组。 (请注意,是否放置代码以使用所有其他变量初始化StudentSpec或稍后在类中放置,所有静态内容都将首先被初始化。)

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

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

答案 1 :(得分:0)

数组索引以0开头,并且给定大小2意味着它只能具有位置0和1 不是2.

 public static String [][] StudentSpect = new String [n][2];
```
And you are accessing array position of 2 over here.
```
 StudentSpect[i][2] = SConverter.append(l).toString();
```
So make this Change

公共静态字符串[] [] StudentSpect =新字符串[n] [3];