2013-12-23 157 views
-1

我不明白我在做什么错误或我怎么得到OutOfBounds例外获取outofbounds错误,不知道我做错了什么?

我的输出

您当前的要素是:{cat dog gerbil }
那是什么,你得到了新的宠物吗?

我的错误是

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4   
at PetFunRunner.insertElement(PetFunRunner.java:67)  
at PetFunRunner.main(PetFunRunner.java:35) 

我的代码是

public static void main(String[] args) 
{ 
    Scanner in = new Scanner(System.in); 

    String[] originalPets = {"cat", "dog", "gerbil"}; 
    printArray(originalPets); 

    // PART A 
    System.out.println("What's the new pet that you got?"); 
    String pet = in.nextLine(); 
    String[] updatedPets = insertElement(originalPets, pet); 
    printArray(updatedPets); 
} 
public static String[] insertElement(String[] origArray, String stringToInsert) 
{ 
    String[] newPets = new String[origArray.length + 1]; 
    int s = newPets.length; 
    newPets[s] = stringToInsert; 
    return newPets; 
} 
+0

在'length-1'处插入新字符串,索引在数组中为0。 –

回答

1

你有两个问题。首先,在insertElement中,您不是将原始数组复制到新数组中。其次,你要在数组的末尾插入新的元素。该数组从0s-1,但您尝试在索引s处插入,这会导致您的例外。

0

当你调用insertElement与3个元素,您的数组的数组newPets将有4 length一个这些元素[0][1][2][3]

然后尝试访问索引等于其长度的元素,即[4]。没有这样的元素,所以你会遇到一个超出界限的例外。

相关问题