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.
You are not checking
num3andnum4properly (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:
Since every subarray (
rowin the example) is an array the above code will loop through them filling them with zeros, taking advantage of thefillmethod of theArraysclass, which you need to import as shown in the example.