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 Using Method Overloading

Samantha Keller
Samantha Keller
7,811 Points

How is the applyGuess(String) method associated with the applyGuess(char) method?

Hi All! I am just a little confused as to how both the applyGuess methods are linked together to run properly. I think its mentioned in the video return applyGuess(letters.charAt(0)); calls the original method but I'm a little confused as to how its associated with our original method since our new method uses 'letters' and the old one uses 'letter' as the variable, unless i have something mistyped, but everything seemed to run fine. Below is my code for that section incase i did just type something up wrong. Thanks in advance! :)

 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;
    }

1 Answer

Hey! The methods are both booleans, so in the end they return a true or false. So your applyGuess(String letters) method first checks the "if(letters.length() == 0)" statement, if it's true, the method just stops and throws the error. But if it's false it will run your second method applyGuess(char letter) that checks if the letter is a hit or not, then the second method simply returns true or false to the first method. Hope this helps :)

Mladen Jovanovic
Mladen Jovanovic
4,662 Points

What I'm wondering, though, is how does our program differentiate between the two "applyGuess" methods, considering that they have the same name and are both booleans.

I do understand that, based on our code, a character will be put into the brackets for the second method, but why wouldn't the program recognize "applyGuess(letters.charAt(0)" as the method that requires a String and give us an error, since it only received a char?