Skip to content
Advertisement

Stack in Java not being able to print in specific order

Currently I’m working on a project that is supposed to be a reverse word guessing game.

This is how it should work:

Enter a word: (input = cheese)
Your word is: _ _ _ _ _ e
What letter do you guess? (input = s)

The use keeps guessing the word until it is fully spelled out. If the user guesses the letter correctly it is revealed if not it is still reveled as shown below

Your word is: _ _ _ _ _ e
What letter do you guess?
Your word is: _ _ _ _ s e
What letter do you guess?
Your word is: _ _ _ e s e
What letter do you guess?
Your word is: _ _ e e s e
What letter do you guess?
Your word is: _ h e e s e
What letter do you guess?
Your word is: c h e e s e
Gameover!

⚠️ Currently I have a stack containing all the letters of the given word as shown below:⚠️
Bottom: c h e e s e :Top

I currently have this code:

while(guesses < letters.size()){
   System.out.print("Your word is: ");
   for(int i = 1; i < letters.size(); i++){
      System.out.print("_ ");
   }
   System.out.println(letters.peek() + test);
   System.out.println("Score: " + score);
   System.out.print("What letter do you guess? ");
   char guess = sc.next().charAt(0);
   if((Object)guess == letters.peek()){
      test += letters.pop();
      score++;
   }
   else{
      test += letters.pop();
      score--;
   }
}

However it is printing this:

Your word is: _ _ _ _ _ e
Score: 0
What letter do you guess? 
Your word is: _ _ _ _ se
Score: 0
What letter do you guess? 
Your word is: _ _ _ ees
Score: 0
What letter do you guess? 
Your word is: _ _ eese
Score: 0
What letter do you guess? 
Your word is: _ hesee
Score: 0
What letter do you guess? 
Your word is: ceseeh
Score: 0
Gameover!

Thank you. If any more information is needed please comment and tell me!

Advertisement

Answer

Your code is incomplete, so I can’t be sure what and where is the issue. To answer your question I’ll assume the issue is that the line System.out.println(letters.peek() + test); prints the word incorrectly.

By doing test += letters.pop(); you are appending letters.pop() to test.

Instead you should prepend letters.pop() to test:

test = letters.pop() + test;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement