Question

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.

Was it helpful?

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.

OTHER TIPS

There is no checking for the values of num3 and num4 in your code. Add proper restrictions as I envisage, you don't what them to be greater thatn num1 and num2 respectively.

If the value of num3 or num4 goes beyond the limit you get the ArrayIndexOutOfBoundException.

This fails when num4 == num2 as you are checking num4 > num2; because num2 is the length of the array while index goes to length-1. Same goes with num3 and num1 comparison. Use num2-1 and num1-1 in the comparison as below:

    int num1=0, num2=0, num3=0,num4=0;
    num1 = input.nextInt();  //<--Input a value >0
    num2 = input.nextInt();  //<--Input a value >0
    int[][] ver = new int[num1][num2];
    int active = 0;
    while(active == 0){
        ver[num3][num4] = 0;
        ++num4;
        if(num4 > num2-1){     // or if(num4 >= num2)
            ++num3;
            num4 = 0;
        }
        if(num3 > num1-1){     // or if(num3 >= num1)
            ++active;
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top