javaarraysloopscreateobject

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


I tried to create object which it's size and how many is defined by the user but there is only one array output.Is there any way to create arrays in a loop?

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]);
            }
        }
    }
}

Solution

  • A 2-dimensional array will work:

    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]));
    }