[英]receiving ArrayIndexOutOfBoundsException but cannot figure out why
this is a university assignment (sample academic report), I thought I was done and going to submit but when I started testing... I keep receiving ArrayIndexOutOfBoundsException on line 60 in main and I cannot see why. 这是大学的作业(学术报告样本),我以为我已经完成并准备提交,但是当我开始测试时……我在main的第60行上继续收到ArrayIndexOutOfBoundsException,我不知道为什么。 I am new to Java but really put a lot of hours into this program.
我是Java的新手,但确实为该程序投入了大量时间。 Any help/advice is much appreciated.
任何帮助/建议,不胜感激。 line 60 = "int credits = Integer.parseInt(input[1]);"
第60行=“国际积分= Integer.parseInt(input [1]);” //im thinking error is something to due with data types???
// im认为错误归因于数据类型??? im lost.
我迷路了。
Course / Grade / Report classes pass data to the main java2pgm1 课程/年级/报告类将数据传递给主要的java2pgm1
When you call split it returns you the an array. 调用split时,它将返回一个数组。 Here you are splitting using (":") You need to check the length of variable input before accessing it.
在这里,您使用(“:”)进行拆分。在访问变量输入之前,需要检查其长度。
String[] input = course.split(":");
int credits = Integer.parseInt(input[1]);
The input array may not contain more than 1 value so it fails 输入数组的值不能超过1,因此失败
The exception will occur when the input from a user does not correspond to the expected format course_number:number_of_credits:grade_received:term_taken
. 当来自用户的输入与预期的格式
course_number:number_of_credits:grade_received:term_taken
不对应时,将发生异常。 In your case for what input value are you running into this exception? 在您的情况下,您遇到了什么输入值? Does it contain a
:
? 它是否包含
:
?
Suggest that you test the length of the input
array before referencing index[n] 建议您在引用index [n]之前测试
input
数组的长度
String[] input = course.split(":");
int credits = Integer.parseInt(input[1]);
Integer term = Integer.parseInt(input[3]);
Course cObject = new Course(input[0],credits,input[2],input[3]);
The above snippet in your main always assumes that the course
String has abc:def:ghi:jkl atleast 3 ":" in it. 上面的摘录始终假定
course
字符串中包含abc:def:ghi:jkl至少3个“:”。 It is always good practice to handle the error case, when the string doesn't have 3 ":". 当字符串没有3“:”时,处理错误情况总是一个好的习惯。 Modify your code to something like below
修改您的代码,如下所示
String[] input = course.split(":");
if(input.length == 4)
{
int credits = Integer.parseInt(input[1]);
Integer term = Integer.parseInt(input[3]);
Course cObject = new Course(input[0],credits,input[2],input[3]);
}
else
{
//show some error message to user
}
here size of input array may be 0 or 1, you can check it by input.length
. 这里输入数组的大小可以是0或1,可以通过
input.length
进行检查。 If size of array is less or equal the element you want to get from array then runtime exception ArrayIndexOutOfBoundsException is thrown. 如果数组的大小小于或等于要从数组中获取的元素,则将抛出运行时异常ArrayIndexOutOfBoundsException。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.