亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何修復 ArrayList java.lang.IndexOutOfBounds

如何修復 ArrayList java.lang.IndexOutOfBounds

呼如林 2023-09-27 16:29:55
我想在我的 arrayList“顏色”中存儲沒有配對的數字,但我的 arrayList 收到此運行時錯誤。main 獲取 n(數組大?。┑妮斎牒?arItems 的輸入,然后將 arItems 中的元素轉換為整數,將它們放入 int 數組 ar 中,然后當它調用 sockMerchant 時,它傳遞 int n 和 int 數組 arstatic int sockMerchant(int n, int[] ar) {    ArrayList<Integer> colors = new ArrayList<Integer>(n);    int pairs = 0;    for (int i = 0; i < n; i++) {       if (!colors.contains(ar[i])) {            colors.add(ar[i]);        } else {            pairs++;            colors.remove(ar[i]);        }    }    System.out.println(pairs);    return pairs;}private static final Scanner scanner = new Scanner(System.in);public static void main(String[] args) throws IOException {    // n is the size of the array    // sample n input: 9    int n = scanner.nextInt();    scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");    int[] ar = new int[n];    //sample arItems input: 10 20 20 10 10 30 50 10 20    String[] arItems = scanner.nextLine().split(" ");    scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");    for (int i = 0; i < n; i++) {        int arItem = Integer.parseInt(arItems[i]);        ar[i] = arItem;    }    int result = sockMerchant(n, ar);    scanner.close();}我得到的錯誤是:Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 20 out-of-bounds for length 2    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)    at java.base/java.util.Objects.checkIndex(Objects.java:372)    at java.base/java.util.ArrayList.remove(ArrayList.java:517)    at Solution.sockMerchant(Solution.java:21)    at Solution.main(Solution.java:48)
查看完整描述

1 回答

?
繁花不似錦

TA貢獻1851條經驗 獲得超4個贊

IndexOutOfBoundsException當您嘗試從數組中刪除重復項時,您會收到colors。這是因為remove()的方法ArrayList可以接受 anObject或 anint并且您正在傳遞一個int。這意味著您實際上正在嘗試刪除特定索引,在您的示例中是索引 20,但該索引在您的數組中不存在。


您可以修改代碼以根據索引正確刪除值。


static int sockMerchant(int n, int[] ar) {

    ArrayList<Integer> colors = new ArrayList<Integer>(10);

    int pairs = 0;


    for (int i = 0; i < n; i++) {

       if (!colors.contains(ar[i])) {

            colors.add(ar[i]);

        } else {

            pairs++;

            colors.remove(color.indexOf(ar[i]));

        }

    }


    System.out.println(pairs);

    return pairs;

}


查看完整回答
反對 回復 2023-09-27
  • 1 回答
  • 0 關注
  • 108 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號