我想在特定的位置插入一個元素,但代碼拋出插入元素不會發生
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;
}
你爲什麼不使用https://docs.oracle.com/javase/7/docs/api/java/util/List.html#add (int,%20E) 像這樣: insertArr.add(pos,key); –
我想做一些編碼練習,所以編寫我自己的排序數組的方法。 –
除了編寫自己的代碼我建議你*閱讀*一些標準的代碼。他們中的大多數都包含評論,記錄良好並且關心許多以前你不知道的事情;)至少,它對我有幫助。 – ADS