简体   繁体   中英

Java ArrayIndexOutOfBound Exception

I am trying to run this code and I keep getting the ArrayIndexOutOfBound Exception error.

public class Heisenberg {
 public static void main(String[] args)  {
    int[] array1 = new int[5];
    int[] array2 = new int[5];

    Ext(-1, 10, array1, array2);
  } 

 public static void Ext(int q, int w, int[] e, int[] r)  {
    if (q >= 0)
      e[q] = w;
      r[q] = w;
  }
}

I am a little new to arrays so all help is appreciated. enter code here

Your problem is, that without braces, the if applies only to the following statement:

 if (q >= 0)
  e[q] = w;
  r[q] = w;  // <---- here you get ArrayIndexOutOfBound Exception

add braces like:

if (q >= 0){
  e[q] = w;
  r[q] = w;
}

将开括号和闭括号放在if条件下。

Error is happening in following line:

r[q] = w;

As this out of if block, value of q is -1 which is causing the error.

Move it into if block:

if (q >= 0){
  e[q] = w;
  r[q] = w;
}

Cheers !!

You call method Ext with parameter q with value -1 . Then you accesing the r[q] = w; with -1 which is not defined (array of size 5 is defined on index 0-4).

Why you accesing that?

if (q >= 0)
  e[q] = w;
  r[q] = w;

This means that if-statement is only compared for the e[q] = w; If you want to have all the code covered by if-statement, you need add braces. If no braces are in if-statement, only the first task is connected to that if :

if (q >= 0){
  e[q] = w;
  r[q] = w;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM