A few things that I noticed from a cursory glance:
.replace()
returns a String
, it will not modify option
unless you do:
option = option.replace(guess, "_");
- Also, since you don't want to use Arrays, I highly suggest that you use StringBuilder
EDIT 1 (based off of comment from duplicate thread):
You can use a StringBuilder
to have a String that's initialized to all -
. Then when someone guess a correct letter, you can replace the -
with the guess
.
StringBuilder sb_word = new StringBuilder(lengthOfOriginalString);
for (int i = 0; i < length; i++)
sb_word.append('-'); //add hyphens to StringBuilder, StringBuffer would also work
You should really use something like:
final char blank = '-';
Then, after someone makes a guess
, if you've determined that the character at position i
should be replaced by guess
, you could do:
sb_word.setCharAt(i, guess.charAt(0));
EDIT 2:
while (bodyparts > 0 && !win) //play game while you have bodyparts and haven't won
{
System.out.printf("Word to guess: %s\nEnter a letter or word guess: " , sb_word);
guess = keyboard.next();
if (guess.length() == 1)
{
for (int i = 0; i < length; i++) //loop to see if guess is in originalString
if (Character.toLowerCase(word.charAt(i)) ==
Character.toLowerCase(guess.charAt(0)))
{ //it is, so set boolean contains to be true and replace blank with guess
sb_word.setCharAt(i, guess.charAt(0));
contains = true;
}
if (!contains)
{
bodyparts--;
System.out.printf("Incorrect, you have %d bodyparts left.\n", bodyparts);
}
else if (sb_word.indexOf(String.valueOf(blank)) == -1)
{ //all the letters have been uncovered, you win
win = true;
System.out.println(word);
}
else
{
contains = false;
System.out.println("Good guess.");
}
}
else
{
if (guess.equals(word))
win = true;
else
{
bodyparts = 0;
System.out.printf("Incorrect, you have %d bodyparts left.\n" , bodyparts);
}
}
}