【发布时间】:2018-08-19 20:11:11
【问题描述】:
我有一个主类,要求用户写一个数字(int num)。这个数字将是另一个类中数组的大小。我将使用 Math.random 填充该数组。
这是主类:
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();
}
这是另一个类:
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;
}
现在,假设我在主类中键入“5”。这是我将得到的输出。
Write amount of numbers between 0-99:
5
You chose: 5 With size: 0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
因此,显然变量 num 被设置为用户指定的数字。但是,不知何故,考虑到它打印 0,该数组似乎无法“获取”该数字。这是为什么呢?
【问题讨论】: