3

I want to create a matrix in java .. I implemented the following code

public class Tester {

    public static void main(String[] args) {

        int[][] a = new int[2][0];
        a[0][0] = 3;
        a[1][0] = 5;
        a[2][0] = 6;
        int max = 1;
        for (int x = 0; x < a.length; x++) {
            for (int b = 0; b < a[x].length; b++) {
                if (a[x][b] > max) {
                    max = a[x][b];
                    System.out.println(max);

                }

                System.out.println(a[x][b]);

            }

        }

        System.out.println(a[x][b]);


    }
}

When I run the code I get the following error :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at shapes.Tester.main(Tester.java:8)

I tried different methods to correct the code but nothing was helpful Can you please correct the code for me ?

thank you

2
  • It doesn't really make any sense of creating a 2d matrix which the second dimension consist of no dimension. Decide: a 1 dimension array, or a 2 dimension with at least size 1 for each dimension
    – lazary
    Apr 29, 2016 at 13:49
  • by the way your b variable will not be visible outside of for loop
    – MGoksu
    Apr 29, 2016 at 13:51

2 Answers 2

6

When you instantiate an array, you're giving it sizes, not indices. So to use the 0th index, you need at least a size of 1.

int[][] a = new int[3][1];

This will instantiate a 3x1 "matrix", meaning that valid indices for the first set of brackets are 0, 1 and 2; while the only valid index for the second set of brackets is 0. This looks like what your code requires.

public static void main(String[] args) {

    // When instantiating an array, you give it sizes, not indices
    int[][] arr = new int[3][1];

    // These are all the valid index combinations for this array
    arr[0][0] = 3;
    arr[1][0] = 5;
    arr[2][0] = 6;

    int max = 1;

    // To use these variables outside of the loop, you need to 
    // declare them outside the loop.
    int x = 0;
    int y = 0;

    for (; x < arr.length; x++) {
        for (; y < arr[x].length; y++) {
            if (arr[x][y] > max) {
                max = arr[x][y];
                System.out.println(max);
            }
            System.out.println(arr[x][y]);
        }
    }

    // This print statement accesses x and y outside the loop
    System.out.println(arr[x][y]);
}
1
  • Shouldn't be "max = arr[x][y];" instead of "max = arr[x][b];" ?
    – Cenk
    Apr 5, 2020 at 5:14
1

Your storing 3 elements in the first array.

try this int[][] a = new int[3][1];

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.