I have one main class where the user is asked to write a number (int num). This number will be the size of an array in another class. I will populate that array using the Math.random.
This is the Main class:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Write amount of numbers between 0-99: ");
int num = input.nextInt();
IckeMain im = new IckeMain();
im.setNum(num);
im.fillArray();
}
This is the other class:
public class IckeMain {
Scanner inread = new Scanner (System.in);
int num;
int [] array = new int [num];
int [] nyArr = new int [num];
public void fillArray () {
System.out.println("You chose: " + num + " with size: " +array.length);
for (int j=0; j<num; j++) {
array[j] = (int)(Math.random() * 99);
System.out.println("Unsorted: " +array[j]);
}
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
Now, let's say that I type "5" in the main class.. this is the output that I'll get.
Write amount of numbers between 0-99:
5
You chose: 5 With size: 0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
So, apparently the variable num, is set to the number specified by the user. But, somehow, the array can't seem to "get" that number considering it prints 0. Why is that?