I assume your hand
is represented as something like "ABCDE". Your code is wrong. Let's take a look at the inner loop body:
for (int i = 0; i < hand.length(); i++) {
for (int j = 0; j < hand.length(); j++) {
if (i == 0) { // take a look at this line
x = hand.charAt(0);
counter++;
} else if (x == hand.charAt(i)) {
counter++;
}
}
}
I've commented the line you should look at. The i
will be always be 0 at first outer loop iteration so you'll increase your counter hand.length()
times (that's how many times inner loop will execute while i == 0
). If your hand length is 4 or more your method will always return true
. Moreover even if you'll fix this part it won't help as you're always comparing chars to the first char of the string.
As a suggestion you can get a char array from your string, sort it and look how many identical chars are going one by one:
private boolean hasFourOfaKind(String hand) {
if (hand == null || hand.length() == 0) {
return false;
}
char[] chars = hand.toCharArray();
Arrays.sort(chars);
char current = chars[0];
int count = 1;
for (int i = 1; i < chars.length; i++) {
char next = chars[i];
if (current != next) {
current = next;
count = 1;
} else {
count++;
if (count == 4) {
return true;
}
}
}
return false;
}