I am trying to code a little console program (no swing, no awt, just console). But I am having some trouble and I am not sure if its my logic, or my code, or possibly both?!
Anyways heres what I currently have, I have not taken into consideration a user winning by guessing the word yet. Just working on displaying the hidden word and updating it with respect to the users guesses.
I have viewed all of the threads revolving around this problem at this site and haven't been able to figure this out yet.
The output now will show: -e-- if the user entered e. But when it goes to the next line it is ----. Any thoughts?
Anyways heres what I currently have, I have not taken into consideration a user winning by guessing the word yet. Just working on displaying the hidden word and updating it with respect to the users guesses.
Code:
public class whatever {
public static void main(String[] args) {
List<String> alpha = new ArrayList<String>(); //list of letters user can choose from
int maxTries = 7;
// final int maxWordLen = 25;
// int wrongGuesses = 0;
// int correctGuess;
// String guess;
String hiddenWord ="";
String correctChars= ""; // previously correctly guessed chars
String guessX = ""; // the new guess
String wordList [] = {"car", "desk"};
//select a word from array
int word = 0 + (int) (Math.random() * 2);
String secretWord = wordList[word];
for(int x = 0; x<secretWord.length(); x++)
{
hiddenWord += "-";
}
System.out.println("This is the hidden word: "+hiddenWord);
//System.out.println("The secret word is: "+secretWord);
//Add alphabet to list
alpha.add("a");
alpha.add("b");
alpha.add("c");
alpha.add("d");
alpha.add("e");
alpha.add("f");
alpha.add("g");
alpha.add("h");
alpha.add("i");
alpha.add("j");
alpha.add("k");
alpha.add("l");
alpha.add("m");
alpha.add("n");
alpha.add("o");
alpha.add("p");
alpha.add("q");
alpha.add("r");
alpha.add("s");
alpha.add("t");
alpha.add("u");
alpha.add("v");
alpha.add("w");
alpha.add("x");
alpha.add("y");
alpha.add("z");
//below here is good,kinda
while(maxTries > 0 )
{
System.out.println(hiddenWord);
System.out.println("Here are your letters to chose from\n"+alpha);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please make a guess: ");
try
{
guessX = br.readLine();
}
catch (IOException ioe)
{
System.out.println("IO error!");
System.exit(1);
}
// if in word use String newSecret and display correct letters
if(guessX.indexOf(secretWord)!= 0 )
{
alpha.remove(guessX);
String newSecret= secretWord.replaceAll("[^"+correctChars+guessX+"]", "-");
hiddenWord = newSecret;
System.out.println(hiddenWord);
}
else
{
System.out.println("Sorry your guess is not in the word");
maxTries --;
}
System.out.println("You have "+maxTries+" chances remaining");
}//while
}
}
The output now will show: -e-- if the user entered e. But when it goes to the next line it is ----. Any thoughts?
Comment