Heniammm Heniammm - 1 month ago 19
Java Question

five hand card game and couldn't figure out, badugi & four of a kind

am trying to find four of a kind in a five-card poker hand. but it's not working and couldn't figure out why.

public boolean hasFourOfaKind(String hand) {
int counter = 0;
char x = 0;

for (int i = 0; i < hand.length(); i++)
{
if (i == 0) {
x = hand.charAt(0);
} else if (x == hand.charAt(i)) {
counter++;

}
}
if (counter >= 4) {
return true;
} else {
return false;
}
}


the same problem here am trying to check whether the given four-card hand is a badugi

public boolean hasFourCardBadugi(String hand) {
int diffcounter = 0;
char badugi = 0;

for (int i = 0; i < hand.length(); i++) {
if (i == 0) {
badugi = hand.charAt(0);
} else if (badugi != hand.charAt(i)) {
diffcounter++;
}
}
if (diffcounter >= 10) {
return true;
} else {
return false;
}
}

Answer

Let's look at your for loop.

    for (int i = 0; i < hand.length(); i++) 
    {
        if (i == 0) {
            x = hand.charAt(0);
        } else if (x == hand.charAt(i)) {
            counter++;
        }
    }

In this part

        if (i == 0) {
            x = hand.charAt(0);
        }

You set x to the first card. But you never count that card. You need to add:

        if (i == 0) {
            x = hand.charAt(0);
            counter++;
        }

Of course this still has the issue that it will not detect hands where the four of a kind does not match the first card (ace two two two two), but you should be able to work that out now that the basic bug is fixed. One way to do it would just involve a second loop.