简体   繁体   English

Java ArrayIndexOutOfBound异常

[英]Java ArrayIndexOutOfBound Exception

I am trying to run this code and I keep getting the ArrayIndexOutOfBound Exception error. 我正在尝试运行此代码,并且不断收到ArrayIndexOutOfBound异常错误。

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 适用于以下语句:

 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; r [q] = w;

As this out of if block, value of q is -1 which is causing the error. 由于此if块之外,q的值为-1 ,这导致了错误。

Move it into if block: 将其移入if块:

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

Cheers !! 干杯!

You call method Ext with parameter q with value -1 . 您用值-1参数q调用方法Ext。 Then you accesing the r[q] = w; 然后添加r[q] = w; with -1 which is not defined (array of size 5 is defined on index 0-4). -1(未定义)(大小为5的数组在索引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; 这意味着仅对e[q] = w;比较if语句e[q] = w; If you want to have all the code covered by if-statement, you need add braces. 如果要使所有代码都被if语句覆盖,则需要添加花括号。 If no braces are in if-statement, only the first task is connected to that if : 如果if语句中没有大括号,则如果满足以下条件,则仅第一个任务与之连接:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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