I\'m stuck on a java assignment for a class where we need to make a Hangman game but a REALLY BASIC one (It\'s an intro to Java class). Basically I have a word entered by someon
Hey Jordan, your first attempt looks very good! You only need some more logic inside the while loop to read guesses and replace "*"s with correct guesses. And I would advise you to store the obfuscated word ("*****...") in a string also instead of just printing it out, will be handy later on..
Judging by your code you don't need any help on user input, your only problem is correct replacing of stars with right guesses, lets get to it:
String secret;
//read in secret string
String displaySecret;
//generate as many "*"s as secret is long and store them in displaySecret
Now the cool thing is this:
...no repeated letters...
which will make your assignment much easier! Look at the documentation of the String class provided by Williwaw. There you'll find two methods with which will lead to the solution:
I think from that you'll find the solution easily. Feel free to ask further questions in the comments!
EDIT: Some more help
String secret = "example-text";
String displaySecret = "";
for (int i = 0; i < secret.length(); i++)
displaySecret += "*";
char guess;
//read in a guess
int position = secret.indexOf(guess);
//now position contains the index of guess inside secret, or
//-1 if the guess was wrong
String newDisplaySecret = "";
for (int i = 0; i < secret.length(); i++)
if (i == position)
newDisplaySecret += secret.charAt(i); //newly guessed character
else
newDisplaySecret += displaySecret.charAt(i); //old state
displaySecret = new String(newDisplaySecret);
Damn I was sure there was some kind of setCharAt(int) method.. the loop does the job.