Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a matrix in java

Tags:

java

matrix

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

like image 949
Ali12 Avatar asked Oct 17 '25 01:10

Ali12


2 Answers

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]);
}
like image 177
Zach Posten Avatar answered Oct 19 '25 14:10

Zach Posten


Your storing 3 elements in the first array.

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

like image 25
Minh Kieu Avatar answered Oct 19 '25 15:10

Minh Kieu



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!