我尝试用随机数填充数组,但 IDE 甚至无法使用单个数组。数组初始化有问题。根据 Schildt 的 Java SE 8 指南,可以像我一样创建几个数组,但如果我尝试对其中任何一个数组执行某些操作,则会收到如下所示的错误。
如果我只初始化 1 个数组,则不会出现错误。但是,如果我需要使用许多数组,我应该如何初始化它们?逐个?我在 C++ 中没有遇到过这样的事情。
我知道创建 2D 数组更好,但我现在有一个使用一些 1D 数组的练习。
P.S:如果你不介意的话,还有一个问题。是否可以索引这些数组以便稍后在循环内操作它们。也许借助枚举或什么?
public static void main(String[] args) {
int [] a,b,c,d,e,f,g,h,i = new int[4];
//int a[],b[],c[],d[],e[],f[],g[],h[],i[] = new int[4]; - this doesn't work either
Random random = new Random();
for (int y=0; y<4; y++) {
a[y] = random.nextInt(9); //The local variable a may not have been initialized
System.out.print(a[y] + " "); //The local variable a may not have been initialized
}
}
最佳答案
如果你有固定数量的“长度为 4 的 int 数组”,你可以创建一个 2D 数组,而不是多个长度为 4 的一维数组。 这看起来像这样:
int[][] a = new int[9][4]
//here 9 is the number of arrays you tried to create above, and 4 is the initial length
关于java - 为什么我不能一次初始化多个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54570942/