[英]Why do I get an exception error when I try output an array?
I have written a simple code that is supposed to output a 2D array.我写了一个简单的代码,应该输出一个二维数组。 This is the code:这是代码:
String month[];
int speedfines[][];
public int speedFines() {
speedfines = new int[3][2];
month = new String[2];
month[0] = "JAN";
month[1] = "FEB";
month[2] = " MAR";
speedfines[0][0] = 128;
speedfines[0][1] = 135;
speedfines[0][2] = 139;
speedfines[1][0] = 155;
speedfines[1][1] = 129;
speedfines[1][2] = 175;
speedfines[2][0] = 129;
speedfines[2][1] = 130;
speedfines[2][2] = 185;
speedfines[3][0] = 195;
speedfines[3][1] = 155;
speedfines[3][2] = 221;
System.out.println(Arrays.toString(speedfines));
return 0;
}
When I run this code it gives me java exception in thread error.当我运行此代码时,它在线程错误中给了我 java 异常。 I am using netbeans 12.0 and I do not have any errors in my code but when I run I get the exception error error Can someone explain to me what the java exception means and how to fix it if possible.我正在使用 netbeans 12.0 并且我的代码中没有任何错误,但是当我运行时出现异常错误错误 有人可以向我解释 java 异常的含义以及如何修复它(如果可能)。
The problem is the sizes you defined for the arrays month
and speedfines
.问题是您为数组month
和speedfines
定义的大小。
For example, you defined size 2 to month and tryed to put 3 elements into it.例如,您将大小2定义为月并尝试将3 个元素放入其中。 To your code work properly, change the arrays definitions to:为了您的代码正常工作,请将数组定义更改为:
speedfines = new int [4][3];
month = new String [3];
-------------------
| | | | ⇒ Size = 3 / month = new String [3]
-------------------
↑ ↑ ↑
0 1 2
Your month
array should be:你的month
数组应该是:
month = new String[3];
When you set it to new String[2]
, you are allowing 2
items to be in the array.当您将其设置为new String[2]
,您允许数组中有2
项目。
Since you set 3
items in the array:由于您在数组中设置了3
项目:
month[0] = "JAN";
month[1] = "FEB";
month[2] = "MAR";
It raises the ArrayIndexOutOfBoundsException
, because at this point index 2
does not exist.它引发ArrayIndexOutOfBoundsException
,因为此时索引2
不存在。
Furthermore, your arrays are defined outside the function .此外,您的数组是在函数之外定义的。 Move them inside the function.将它们移动到函数内。
The code should be:代码应该是:
public int speedFines() {
int speedfines[][] = new int[3][2];
String month[] = new String[3];
month[0] = "JAN";
month[1] = "FEB";
month[2] = "MAR";
speedfines[0][0] = 128;
speedfines[0][1] = 135;
speedfines[0][2] = 139;
speedfines[1][0] = 155;
speedfines[1][1] = 129;
speedfines[1][2] = 175;
speedfines[2][0] = 129;
speedfines[2][1] = 130;
speedfines[2][2] = 185;
speedfines[3][0] = 195;
speedfines[3][1] = 155;
speedfines[3][2] = 221;
System.out.println(Arrays.toString(speedfines));
return 0;
}
you save 12 items in array 2dimention so you need to do this speedfines = new int [4][3];
您在数组 2dimention 中保存了 12 个项目,因此您需要执行此操作speedfines = new int [4][3];
I think the exception name is ArrayIndexOutOfBounds that show when you put a size of array and give it items bigger than her size我认为异常名称是 ArrayIndexOutOfBounds 显示当您放置数组大小并为其提供大于她的大小的项目时
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.