Search code examples
javaarraysuser-defined

user defined size of a two dimensional array (Java)


I'm new to java, and i'm trying to make a array who's size is user defined. I'm staring off by filling in the entire array with zeros and moving from there. How should I go about doing that? What I have right now is something similar to: (input being my scanner object)

int num1, num2, num3 = 0, num4 = 0, active = 0;

num1 = input.nextInt();
num2 = input.nextInt();

int[][] ver = new int[num1][num2];

while(active == 0){

    ver [num3][num4] = 0;
    ++num4;

    if(num4 > num2){

        ++num3;
        num4 = 0;
    }

    if(num3 > num1){

        ++active

    }

}

This keeps giving me an ArrayIndexOutOfBoundsException:0, making me think ver[0][0] doesn't exist. Thanks in advance.


Solution

  • You are not checking num3 and num4 properly (they both are allowed to reach the upper bound) so they will eventually go out of bounds.

    Since you're just trying to fill your array with zeros why don't you consider the following code:

    import java.util.Arrays;
    
    // ...
    
    int num1 = 2; // fixed number just for test purposes
    int num2 = 2; // fixed number just for test purposes
    
    int[][] ver = new int[num1][num2];
    for (int[] row: ver)
        Arrays.fill(row, 0);
    
    System.out.println(ver[0][0]); // prints 0 as expected
    

    Since every subarray (row in the example) is an array the above code will loop through them filling them with zeros, taking advantage of the fill method of the Arrays class, which you need to import as shown in the example.