简体   繁体   中英

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. 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.

The problem is the sizes you defined for the arrays month and speedfines .

For example, you defined size 2 to month and tryed to put 3 elements into it. 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 = new String[3];

When you set it to new String[2] , you are allowing 2 items to be in the array.

Since you set 3 items in the array:

month[0] = "JAN";
month[1] = "FEB";
month[2] = "MAR";

It raises the ArrayIndexOutOfBoundsException , because at this point index 2 does not exist.

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]; I think the exception name is ArrayIndexOutOfBounds that show when you put a size of array and give it items bigger than her size

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM