-1

Why it index out of bound?

I nap a picture in ---> PICTURE

Code:

Scanner sc = new Scanner(System.in);
int a=0,b=0,n=0;
int[][] sum;
int q = sc.nextInt();

for(int i=0;i<q;i++){

    a = sc.nextInt();
    b = sc.nextInt();
    n = sc.nextInt();
    sum = new int[i][n];

    sum[i][0] = a +  (int)Math.pow(2,0) * b;

focus on this

    sum = new int[i][n];
    sum[i][0] = a +  (int)Math.pow(2,0) * b;

Input:

1
5 3 5

Exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at Main.main(Main.java:19)
  • 2
    Please check this post to understand more about `ArrayIndexOutOfBoundsException ` https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it – Nagaraju Chitimilla Sep 20 '21 at 06:20
  • Please don't post code as image. See https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question why. – Reporter Sep 20 '21 at 06:25
  • Here: `sum = new int[i][n];`, when `i = 0` in your first loop iteration, you create an array of size 0. You then try to access the array of size 0 at index 0 here `sum[i][0] = a + (int)Math.pow(2,0) * b;`, which is why you get the exception. See the linked duplicate. – maloomeister Sep 20 '21 at 06:26
  • @user16320675 My edit just displayed the image. – Reporter Sep 20 '21 at 06:27
  • @NagarajuChitimilla Okay i will read rule immediately , Thanks for edit my post ;_; to be good for read. – Green Goblan Sep 20 '21 at 07:02
  • @user16320675 Okay,Thanks you very muchhhhhh. – Green Goblan Sep 20 '21 at 07:02
  • @Reporter Okay , I ' m sorry about my picture. – Green Goblan Sep 20 '21 at 07:03

1 Answers1

0

For your first iteration, i = 0 and you initialized an int array (int[0][5]) which is an empty array. size is 0, 5.

And at the same time you are accessing an element at the position 0. In order to get an element at position 0 then the size of the array should be > 0.

user16320675
  • 135
  • 1
  • 3
  • 9
Hassan Liasu
  • 101
  • 3
  • 7