有没有办法在 JAVA 中循环创建数组?

Is there any way to create arrays in a loop in JAVA?

我试图创建大小和数量由用户定义的对象,但只有一个数组 output.Is 有什么方法可以在循环中创建数组?

public class Somehthing {    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Scanner sc2 = new Scanner(System.in);
        Random rnd = new Random();
        System.out.println("How many array?:");

        for (int j = 0; j <= sc.nextInt(); j++) {
            System.out.println("Define array size:");
            int[] dizi = new int[sc2.nextInt()];
            for (int i = 0; i <= dizi.length - 1; i++) {
                int deger = rnd.nextInt(1000000);
                dizi[i] = deger;
                System.out.println(array[j]);
            }
        }
    }
}

一个二维数组可以工作:

Scanner sc = new Scanner(System.in);
Random rnd= new Random();

System.out.println("How many array?:");
int[][] array = new int[sc.nextInt()][];
for(int j = 0; j < array.length; j++){
    System.out.println("Define array size:");
    array[j] = new int[sc.nextInt()];
    for(int i = 0; i < array[j].length; i++){
        array[j][i] = rnd.nextInt(1000000);
    }
    System.out.println(Arrays.toString(array[j]));
}

我不确定我是否理解正确,但是如果你想创建 n 个数组,那么你所要做的就是使用一个新的数据结构来拿着你的阵列;例如 ArrayList(您可以使用二维数组来存储信息,但多维数组往往会变得非常复杂,速度非常快;这更简单。

所以需要稍微修改一下:

public static void main(String[] args) {


  Scanner sc = new Scanner(System.in);
  Scanner sc2 = new Scanner(System.in);  //I don't understand why you used a second scanner
  Random rnd= new Random();
  ArrayList<Integer[]> arrays = new ArrayList<>();  //you must import java.utils.ArrayList;
  System.out.println("How many array?:"); 

  for(int j=0;j<=sc.nextInt();j++){
     System.out.println("Define array size:");
     Integer[] array = new int[sc2.nextInt()];
     for(int i=0;i<=array.length-1;i++){
       int value=rnd.nextInt(1000000);
       array[i]= value;
       System.out.println(array[j]);
       }
     arrays.add(array); //You are adding this array into your List of arrays.
   }
}

Remember to use the wrapper class Integer() with Lists, primitive types will not work. If you need to know why, then read this stack-overflow answer or this tutorial for Generics.

我没有花时间优化你的代码,因为我试图只解决你的problem/question。