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 Delivering the MVP Arrays and Command Line Arguments

Christian Thieme
Christian Thieme
9,448 Points

On the boolean applyGuess method, how are we adding char letter to the variable hits, since hits is a string?

My question is about the following code:

public boolean applyGuess(String letters){
  if (letters.length()== 0) {
    throw new IllegalArgumentException("No letter found");
  }
     return applyGuess(letters.charAt(0));
 }

 public boolean applyGuess(char letter) {
 letter = normalizeGuess(letter);
  boolean isHit = answer.indexOf(letter) != -1;
  if (isHit) {
    hits += letter;
  } else {
    misses += letter; 
  }
  return isHit;
 } 

On the boolean applyGuess method, how are we adding char letter to the variable hits or misses, since hits and misses are strings? Just curious, as I thought you could not just add char's to Strings.

Thanks!

2 Answers

Lukas Baumgartner
Lukas Baumgartner
14,817 Points
public boolean applyGuess(String letters){
        if (letters.length()== 0) { 
         throw new IllegalArgumentException("No letter found"); 
        } 
   return applyGuess(letters.charAt(0)); 
}

public boolean applyGuess(char letter) { 
   letter = normalizeGuess(letter); 
   boolean isHit = answer.indexOf(letter) != -1;
    if (isHit) {
      hits += letter; 
   } else { 
      misses += letter; 
   } return isHit;
}

Of course you can append a char to a String. A String is in fact an Array of chars. It doesn't work the other way round though (at least that simple) .

Jasmeet Singh
Jasmeet Singh
20,145 Points

Yes. We can append both a String as well as a Character to a String.