I have to write a hangman homework assignment. We aren't allowed to use any char array and only use String methods to manipulate the string itself. A problem I'm running into is when I try to check the string builder for duplicates.
This is my hangman method
public void playHangMan(Scanner guessWord)
{
int error = 6;
String letter;
boolean vali, dup;
displayHangman();// call displayHangman method
// get input, lower case input, and then validate in a loop
do
{
letter = guessWord.nextLine();
letter = lowerGuess(letter); // call lowerGuess method
vali = letter.matches("[a-z]");
dup = checkDup(letter); // call checkDup method
if(vali == false)
{
System.out.print("Please enter only a SINGLE letter: ");
}
else if(dup == true)
{
System.out.print("Duplicated letter, please enter another: ");
}
if(dup == false && vali == true)
{
this.guessAns.append(letter);
}
}
while(vali == false && dup == false);
}// end playHangman method
My duplicate method:
private boolean checkDup(String letter)
{
int i;
boolean dup = false;
// check guessAns StringBuilder for duplicate letters
for(i = 0; i <= this.guessAns.length() - 1 && dup == false; i++)
{
if(letter.equals(this.guessAns.charAt(i)))
{
dup = true;
}
}
if(dup == true)
{
return true;
}
else
{
return false;
}
}// end checkDup method
The problem is that my checkDup method isn't finding any duplicates. I tried appending the letter a into my string builder and entering in the value a for letter, but still no luck. Can it be that letter.equals(this.guessAns.charAt(i)) is comparing a String to a Char and that's why my checkDup method is failing to find duplicates? Can someone explain a way that I can get around this? Any help will be greatly appreciated.
2 ways you could work around this:
letter.charAt(0) == guessAns.charAt(i);
The solution above is under the assumption that letter is a single char.
The other way is to invoke Character.toString on the char:
letter.equals(Character.toString(guessAns.charAt(i)));
Calling String.equals(char) will always return false, as Strings never compare as equal to Characters. Do this to compare them as characters:
if(letter.charAt(0) == this.guessAns.charAt(i)) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With