Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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