Need to write a sort method for my project.. Its a cardgame. These are the specs for the method.
Below is the code I have so far, working but need to handle nulls and not full arrays(hand). Any suggestions or pointers would be appreciated. Thanks.
public void sortHand(){
// loop over every slot
for (int i = 0 ; i < cards.length; i++) {
for (int j = i+1 ; j < cards.length; j++) {
//getValue returns face value of card
if(cards[j].getValue().compareTo(cards[i].getValue()) < 0) {
//swap
Card temp = cards[i];
cards[i] = cards[j];
cards[j] = temp;
}
else {
isSorted = false;
}
}
}
isSorted = true;
}
Your code doesn't assume any particular number of cards, so it already handles non-full hands. Nothing needed there.
if(cards[j].getValue().compareTo(cards[i].getValue()) < 0)
You need to handle the cases where cards[i] or cards[j] is null. You don't want to call .getValue() on a null value; it'll throw a NullPointerException.
There are three cases to handle: one card is null, the other one is null, or both are. If they're both null you don't need to swap anything. If one is null but not the other, you need to decide if null goes first or last. In one case you'll swap and in the other you'll do nothing.
if (cards[i] == null && cards[j] == null) {
// no swap
}
else if (cards[i] == null && cards[j] != null) {
// swap if nulls go last, otherwise do nothing
}
else if (cards[i] != null && cards[j] == null) {
// swap if nulls go first, otherwise do nothing
}
else if (cards[j].getValue().compareTo(cards[i].getValue()) < 0) {
...
}
I leave it as an exercise to combine the appropriate "swap" cases into a single if using ||. Be careful! You need to do make sure neither card is null before you call .getValue(). The order of the checks is crucial.
else { isSorted = false; }
There's no need for this clause, by the way. Just set isSorted to true at the end of the method. You don't need to set it to false in the middle of sorting. Nobody's going to check the flag while you're actively sorting the hand.