我不明白我在做什么错误或我怎么得到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;
}
在'length-1'处插入新字符串,索引在数组中为0。 –