java - 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();
}
}
}
解决方案
首次加载类时会执行静态代码。这意味着,您在方法运行StudentSpec
之前进行初始化。main
这反过来意味着n
尚未分配值,因此它默认为 0。因此,它StudentSpec
是一个维度为零乘二的数组。(请注意,无论您是将代码StudentSpec
与所有其他变量一起初始化还是稍后在类中初始化,所有静态内容都会首先初始化。)
然后你的代码main
运行,调用GetStudentsNumber
,它设置n
,但不初始化StudentSpec
(再次)。然后GetStudentSpect
运行,一旦你尝试访问StudentSpec
,你的程序就会崩溃,因为它是一个元素为零的数组。
要解决此问题,请StudentSpec
在GetStudentsNumber
读取后n
初始化,即将代码从静态初始化程序移动到此方法。
推荐阅读
- javascript - 使用“inspect”(字符串!)调用代理获取陷阱
- node.js - 集群和分叉是一样的吗?
- matlab - 在 MATLAB 中查找 2 列数组中的第一个零行
- .net - .net 核心异步/等待 tcp 与 linux
- c# - 如何在 xamarin 表单中为框架提供阴影效果
- ember.js - Ember.js 从 url 获取 JSON 数据
- php - Laravel 循环遍历所有列
- git - 在 GUI 中浏览单个文件的 git 提交历史记录
- java - 在安全请求上触发 Spring Security 登录?
- python - Python如何忽略或修复“IndexError:列表索引超出范围”?