2013-07-18 91 views
3

在这种情况下是否可以避免ArrayIndexOutOfBoundsException?如何避免在这种情况下ArrayIndexOutOfBoundsException?

package com; 

public class Hi { 

    public static void main(String args[]) { 

     String[] myFirstStringArray = new String[] { "String 1", "String 2", 
       "String 3" }; 

     if (myFirstStringArray[3] != null) { 
      System.out.println("Present"); 
     } else { 
      System.out.println("Not Present"); 
     } 

    } 

} 
+2

总是有可能避免一个ArrayIndexOutOfBoundsException,核对'array.length'访问你到底想达到数组元素 –

+1

过吗? –

+1

你的数组将*总是*长度为3,所以索引3 *总是*无效。目前还不清楚你在问什么,但是当你继续使用一个长度为3的数组并且要求索引3时,答案是否定的:你无法避免一个异常。 –

回答

5

也许我不明白真正的问题,但是在这种情况下,在访问它之前是否阻止您检查索引是否在数组中?

if (myIndex < myFirstStringArray.length) { 
    System.out.println("Present"); 
} else { 
    System.out.println("Not Present"); 
} 
2

在数组中,它们的测量方式与数字不同。数组中的第一个对象被认为是0,所以,在你的if语句,而不是3,你只是把2

if (myFirstStringArray[3] != null) { 
     System.out.println("Present"); 

if (myFirstStringArray[2] != null) { 
     System.out.println("Present"); 

希望这有助于! :)

0

String您的String数组包含3个元素,并且您正在访问数组[3],即第4个元素作为基于0的索引,因此您会收到此错误(异常,无论如何)。

为避免ArrayIndexOutOfBoundsException在指定的索引范围内使用索引。并且始终检查您的索引是否为>=array.length

相关问题