For Loop and String Problem - Console Hangman Game
I am doing my Hangman Project and need assistance. I am doing the first part, have managed to hide the word using (*), but now the problem I am facing is. After I first guess I need it to replace (*) with appropriate letter. But with the code below here is my output. The word in this example is "hello"
Welcome to Hangman... v1.0 - Designed Ashley Bwanya
This is the word you have to guess:
* * * * *
Enter your first guess
h
h* *
import java.util.Scanner;
public class Hangman
{
public static void main(String[] args)
{
int attempts = 6;
String secret;
String displaySecret = "";
Scanner scn=new Scanner(System.in);
Game myWord = new Game();
secret = myWord.getWord();
for (int i = 0; i < secret.length(); i++)
{
displaySecret += " * ";
}
System.out.println("Welcome to Hangman... v1.0 - Designed Ashley Bwanya");
System.out.println("This is the word you have to guess: \n");
System.out.println(displaySecret+ "\n");
System.out.println("Enter your first guess");
char firstGuess = scn.nextLine().charAt(0);
int position = secret.indexOf(firstGuess);
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);
System.out.println(newDisplaySecret);
}
}
Re: For Loop and String Problem - Console Hangman Game
I don't want to ruin the challenge for you but if you would like you can take a look at my java hangman example... http://www.javaprogrammingforums.com...a-hangman.html however keep in mind that I am a beginner here as well but I did manage to get that part of my program to work just fine using a StringBuilder. This allowed me to modify a string where as a String is immutable.
String word = "";
for(int i = 0; i < secret.length(); i++){ // display dashes for length of word
word += "-";
}
StringBuilder guessedWord = new StringBuilder(word);
System.out.println(guessedWord); // print number of dashes for word
for(int i = 0; i < guessedWord.length(); i++){ // check for letter in word
if(guess == secret.charAt(i)){
guessedWord.setCharAt(i, guess);
}
}//end for