-4

I am trying to insert data to multidementional array, but 'for loop' inside for loop(inner 'for loop') not running (when i run the code inner loop not runnig only other 'for loop')you can clearly see that at result i attached with this quection.

Some code:

for(int s=0;s<=y;s++){  //y mean number of arrays, user can input any number for y in here y>=2
     int w=s+1;
     System.out.println("number of data for array"+" "+w+':');
     int night[][]=new int[s][x.nextInt()];
     for(int counter=0;counter<night.length;counter++){
         int m=counter+1;
         System.out.println("insert the number"+m+":");
         night[s][counter]=x.nextInt();

     }
}

I am still learning Java please tell me why this not working

This is the result when i run that code

how much Arrays:
4
number of data for array 1:
6
number of data for array 2:
7
insert the number1:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at practice.Multi_array_data_input.main(Multi_array_data_input.java:42)
S.Sachith
  • 536
  • 1
  • 9
  • 21

1 Answers1

1

The problem is that you call a index in an array, which does not exists, because arrays in Java and JavaScript are zero-based. When you define an array with int[] array = new int[3] does this mean, that the indexes 0, 1, 2 are available. The index 3 is not part of the array. So to solve the problem you have to minimise the variable s by 1, when you call your night array.

for(int s=0;s<=y;s++){ // y mean number of arrays, user can input any number for y in here y>=2
    int w=s+1;
    System.out.println("number of data for array "+w+':');
    int night[][]=new int[s][x.nextInt()];
    for(int counter=0;counter<night.length;counter++){
        int m=counter+1;
        System.out.println("insert the number "+m+":");
        night[s - 1][counter]=x.nextInt();
    }
}
manud99
  • 458
  • 2
  • 8