Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Objects (Retired) Delivering the MVP Validation

I get the answer in plain text only. I also didn't really understand the for each loop. Could really use some help !

public class Game {
 private String mAnswer;
 private String mHits;
 private String mMisses; 

 public Game(String answer)
 {
 mAnswer = answer;
 mHits = "";
 mMisses = "";  
 } 

 public boolean applyGuess (char letter) 
 {
 boolean isHit = mAnswer.indexOf(letter) >= 0;
   if (isHit)
   {
   mHits += letter;
   } else{
   mMisses += letter;
   }

   return isHit;
 } 

 public String getCurrentProgress(){
 String progress = "";
  for (char letter : mAnswer.toCharArray()){
   char display = '-';
   if(mHits.indexOf(letter) >= 0){
     display = letter;
   } 
     progress += letter;

  }
   return progress;

 } 

}

2 Answers

When I test your code and ask for my current progress I get the answer instead. <br>E.g., if the answer is 'hello' and I've guessed 'h' and 'o' I am getting 'hello' back rather than 'h---o'.

To fix this you need to modify your getCurrentProgress() method so that it displays hyphens for unguessed letters. Here's one way you can do that:

 public String getCurrentProgress() {
   String progress = "";
   for (char letter : mAnswer.toCharArray()){
      if(mHits.indexOf(letter) >= 0){  //if letter found
         progress += letter;           //append letter to progress
      } else {
         progress += "-";              //append hyphen to progress
      }
   }
   return progress;
 } 

Now, re the for-each loop. What it's doing is traversing letter by letter (char by char) through the mAnswer string.
It checks to see if each letter of mAnswer is in mHits or not, using the indexOf method. If the letter is in mHits, it is added to progress. If the letter is not in mAnswer, a - is added to progress instead.

Here's a test program:

public class GameTest {
   public static void main(String[] args) {
      Game g = new Game("hello");
      System.out.println(g.applyGuess('h'));
      System.out.println(g.applyGuess('o'));
      System.out.println(g.applyGuess('t'));
      System.out.println(g.getCurrentProgress());

   }
}

With its output:

true
true
false
h---o

Thanks for the helpful answer! That fixed it