我有一个主类,要求用户写一个数字 (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,该数组似乎无法“获取”该数字。这是为什么?
最佳答案
问题是您在知道数组大小之前就创建了数组。
我会把你的代码改成这样:
public class IckeMain {
Scanner inread = new Scanner (System.in);
int num;
int [] array;
int [] nyArr;
public IckeMain(int num) {
this.num = num;
}
public void fillArray () {
array = new int [num];
nyArr = new int [num];
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;
}
}
在这里您需要传递 num,它是 IckeMain 的构造函数中数组的大小。 所以,而不是
IckeMain im = new IckeMain();
im.setNum(num);
你只需要一行:
IckeMain im = new IckeMain(num);
希望对您有所帮助。
关于java - 将数组大小设置为来自另一个类的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51921449/