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.
Set<Character>orString.indexOf(..).checkDupcan be simplified toreturn dup;.dupvariable.dup = true;withreturn true;and putreturn false;at the end. +1 for a well-written question btw.