我正在尝试在特定位置插入一个元素,但代码抛出错误
java.lang.ArrayIndexOutOfBoundsException
我是java的新手,所以任何人都可以帮我纠正我的代码。我知道在insertPosition方法的insertArr[i+1] = insertArr[i];
中做错了。任何帮助都会得到很好的帮助。
我的代码
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] insertArr = {10,30,20,40,60,50,90,70,80};
Arrays.sort(insertArr);
int arrLength = insertArr.length;
System.out.println("At what position you want to insert");
int pos = in.nextInt();
System.out.println("What element you want to insert");
int key = in.nextInt();
insertPosition(insertArr,arrLength,pos,key);
for(int num : insertArr){
System.out.println(num);
}
}
public static int insertPosition(int insertArr[],int arrLength, int pos, int key){
if(pos > arrLength)
return arrLength;
for(int i=arrLength-1; i>=(pos-1); i--)
insertArr[i+1] = insertArr[i];
insertArr[pos-1] = key;
return arrLength;
}
答案 0 :(得分:2)
您需要确保i小于insertArray长度且大于零。
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] insertArr = {10, 30, 20, 40, 60, 50, 90, 70, 80};
Arrays.sort(insertArr);
System.out.println("At what position you want to insert");
int pos = in.nextInt();
System.out.println("What element you want to insert");
int key = in.nextInt();
insertPosition(insertArr, pos, key);
Arrays.stream(insertArr).forEach(System.out::println);
}
public static void insertPosition(int insertArr[], int pos, int key) {
if (pos >= insertArr.length)
return;
for (int i = insertArr.length - 1; i > (pos - 1) && i < insertArr.length -1; i--)
insertArr[i + 1] = insertArr[i];
insertArr[pos - 1] = key;
}
在java中,数组的长度是不可变的,当您从索引中调用不存在的元素时,您将获得此异常。为了避免在for循环中你要检查i< array.length
或i&lt; array.length -2。
其次,您的插入方法可以简化,如上所述。
答案 1 :(得分:0)
数组的长度在Java中是不可变的,你必须使用某种类型的Collection,例如List / ArrayList
答案 2 :(得分:0)
问题在于这段代码:
for(int i=arrLength-1; i>=(pos-1); i--)
insertArr[i+1] = insertArr[i];
在第一次迭代中,您访问超出最后一个数组索引的insertArr[arrLength]
。所以你应该从i=arrLength-2;
答案 3 :(得分:0)
首先,你必须从变量pos中减去1并验证它是否在数组长度的范围内。
您的代码应如下所示:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] insertArr = { 10, 30, 20, 40, 60, 50, 90, 70, 80 };
Arrays.sort(insertArr);
int arrLength = insertArr.length;
System.out.println("At what position you want to insert");
int pos = in.nextInt();
System.out.println("What element you want to insert");
int key = in.nextInt();
insertPosition(insertArr, arrLength, pos, key);
for (int num : insertArr) {
System.out.println(num);
}
}
public static int insertPosition(int insertArr[], int arrLength, int pos, int key) {
pos = pos - 1;
if (pos >= arrLength || pos < 0)
return arrLength;
for (int i = arrLength - 1; i >= pos; i--) {
insertArr[i] = insertArr[i];
}
insertArr[pos] = key;
return arrLength;
}