Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with Two-Dimensional Arrays

Tags:

java

arrays

First of all, Beginner here.

I'm using this code.

class MDArrays {
    public static void main(String[] args) {
        int[][] x;
        int t=2;
        x = new int[2][3];

        for(int i=0; i<=1; i++) {
            for(int j=0; i<=2; j++) {
                x[i][j] = t;
                t += 2;
                System.out.println(x[i][j]);
            }
        }
    }
}

It compiles perfectly, but when running it, after displaying 3 numbers correctly I'm getting the following error.

Exception in thread "main" java.Lang.ArrayindexOutOfBoundsException : 3 at MDArrays.main(MDArrays.java:13)

Where am I going wrong?

like image 494
DM_Morpheus Avatar asked Jan 22 '26 00:01

DM_Morpheus


2 Answers

You are incrementing j while checking against i.

for(int j=0; i<=2; j++)

j will keep incrementing which will eventually give you an IndexOutOfBoundsException

like image 112
Andres Avatar answered Jan 24 '26 23:01

Andres


for(int j=0; i<=2; j++) {

Is your problem. Try:

for(int j=0; j<=2; j++) {
like image 32
KLee1 Avatar answered Jan 24 '26 22:01

KLee1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!