计算机课实验中ArrayList触发java.lang.IndexOutOfBoundsException的解决求助
java.lang.IndexOutOfBoundsException in Hand.addCard() Method Got it, let's break down why you're hitting this exception and fix your code to meet the lab requirements step by step.
Why the IndexOutOfBoundsException occurs
When you first call addCard (with the Card(4)), your myHand ArrayList is empty (size = 0). Your while loop uses the condition i <= myHand.size()—so 0 <= 0 evaluates to true. Then you call getCardValue(i), which tries to run myHand.get(0)—but since the list has no elements yet, index 0 doesn't exist, hence the exception.
Other logic flaws in your addCard method
Beyond the exception, your code doesn't align with the lab rules and has extra bugs:
- Incorrect loop condition: Using
i <= myHand.size()will always trigger an out-of-bounds error wheniequals the list size (since list indices range from 0 to size-1). - Misaligned insertion logic: The lab asks to find the first Card with a pip value strictly less than
c's value, then insertcat that index. Your checkc.getValue() >= getCardValue(i)doesn't match this requirement, and you don't break the loop after inserting—this would cause infinite loops or duplicate card inserts. - No empty list handling: You need to account for adding the first card without entering the loop.
Fixed Code
Updated getCardValue (with safety check)
While your original getCardValue works for valid indices, adding a check prevents accidental out-of-bounds errors from invalid input:
public int getCardValue(int n) { if (n < 0 || n >= myHand.size()) { throw new IllegalArgumentException("Index " + n + " is out of bounds. Hand size is " + myHand.size()); } return myHand.get(n).getValue(); }
Corrected addCard method
This version follows the lab requirements exactly and fixes the exception:
public void addCard(Card c) { int i = 0; // Find the first index where the existing card's value is strictly less than c's value while (i < myHand.size()) { if (myHand.get(i).getValue() < c.getValue()) { break; // Exit loop once we find the insertion point } i++; } // Insert the new card at the found index (or end if all existing cards are larger) myHand.add(i, c); }
How this works with your test case
Let's walk through your test scenario to confirm it matches the expected output:
- Adding
Card(4):myHandis empty, loop doesn't run—card is added at index 0 →[4] - Adding
Card(10): Loop checks index 0 (4 < 10), breaks, inserts at 0 →[10,4] - Adding
Card(12): Loop checks index 0 (10 <12), breaks, inserts at 0 →[12,10,4] - Adding
Card(14): Loop checks index 0 (12 <14), breaks, inserts at 0 →[14,12,10,4] - Adding
Card(2): Loop runs through all elements (14,12,10,4 are all ≥2),ireaches 4 (equal to list size), inserts at end →[14,12,10,4,2]
When you call h.getCardValue(3), it returns the value at index 3 (4), which matches your expected output.
内容的提问来源于stack exchange,提问作者Marcellus McDuff

