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
19,273 Points

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