I am trying to find four of kind in a 5 poker hand. I don't know where I went wrong, but the JUnit is reporting it's wrong.
public boolean hasFourOfaKind(String hand) {
int counter = 0;
char x = 0;
for (int i = 0; i < hand.length(); i++) {
for (int j = 0; j < hand.length(); j++) {
if (i == 0) {
x = hand.charAt(0);
counter++;
} else if (x == hand.charAt(i)) {
counter++;
}
}
}
if (counter >= 4) {
return true;
} else {
return false;
}
}
Your loop logic is wrong. It is incrementing counter for the same card again. That's why it is failing. In below mentioned code I am considering card only once.
public static boolean hasFourOfaKind(String hand) {
int counter = 0;
for (int i = 0; i < hand.length(); i++) {
counter = 0;
for (int j = 0; j < hand.length(); j++) {
if (hand.charAt(j) == hand.charAt(i)) {
counter++;
}
}
if (counter >= 4) {
return true;
}
}
return false;
}