【问题标题】:"java.lang.ArrayIndexOutOfBoundsException" error in JavaJava 中的“java.lang.ArrayIndexOutOfBoundsException”错误
【发布时间】:2019-07-23 13:56:11
【问题描述】:

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

【问题讨论】:

    标签: java indexoutofboundsexception


    【解决方案1】:

    数组索引从 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];

    
    

    【讨论】:

    • 在初始化 n 个变量之前,您已经初始化了 StudentSpect
    • 在顶部声明这个 public static String [][] StudentSpect;
    • 在 n 初始化后初始化如下:- StudentSpect = new String [n][3];
    • 感谢您的帮助?
    【解决方案2】:

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

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

    要解决此问题,请在读取 n 后将 StudentSpec 初始化为 GetStudentsNumber,即将代码从静态初始化程序移至此方法。

    【讨论】:

    • 我一开始就尝试这样做,但它给出了这个错误:参数 StudentSpect 的非法修饰符;只允许 final
    • 我也修复了这个错误:stackoverflow.com/questions/29086903/…。真的很有帮助,谢谢❤❤❤
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多