I'm doing a lab for my computer science class and my teacher doesn't do emails so I'm asking for help here. To my knowledge this code shouldn't come up with an error, but obviously it is. I need help with this specific example as to, at the very least, why the error is occurring in the first place. My instructions are:
Poker players find it useful to sort their hands so that it's easier to see what kind of hand they have. One way to do this is to sort the cards in order of decreasing pip value. We can do this fairly easily by adding a simple method to the Hand class and editing the definition of that class's addCard method. In the task below, we ask you to:
Define the getCardValue method, which takes an integer n from 0 through 4 and returns the pip value of the Card with index n in this Hand.
Modify the addCard method so that it takes a Card c and uses a while loop to locate the index of the first Card in this Hand whose pip value is strictly less than that of c and then uses the two-input version of the ArrayList.add method to insert c into the Hand at that index.
Provide a definition for the getCardValue method and a new definition for the addCard method in accordance with the description given above.
Here's my code:
import java.util.ArrayList;
public class Hand {
private ArrayList<Card> myHand;
// The class constructor and the getHand and printHand methods are hidden
// Insert definitions for the getCardValue and addCard methods here
public int getCardValue(int n) {
return myHand.get(n).getValue();
}
public void addCard (Card c) {
int i = 0;
while (i <= myHand.size()) {
if(c.getValue() >= getCardValue(i)) {
myHand.add(i, c);
i++;
}
}
}
Here is the code they give me to test, which is supposed to return 4
public static void main( String[] args )
{
Card[] cards = { new Card( "spades", 4 ), new Card( "hearts", 10 ),
new Card( "clubs", 12 ), new Card( "diamonds", 14 ),
new Card( "diamonds", 2 ) };
Hand h = new Hand();
for ( int i = 0; i < 5; i++ )
h.addCard( cards[ i ] );
System.out.println( h.getCardValue( 3 ) );
}
I believe the problem lies somewhere in addCard and I keep getting the error message:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:657)
at java.util.ArrayList.get(ArrayList.java:433)
How can I resolve it?