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) Creating the MVP Prompting for Guesses

Kshatriiya .
Kshatriiya .
1,464 Points

Please explain this boolean code

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

Hello, using boolean as a method is confusing me a bit. As my understanding goes, in order to use boolean in a method, you have to pair it with a return method in the code block. If you look at the code above, it does not have a return method so what exactly does

applyGuess(char letter) store? Without a return, would it not make sense to just declare public void applyGuess(char letter) ?

This is my understanding of how this code works, please do correct me:

public boolean  applyGuess(char letter) \\this is the method
 {
    boolean isHit = mAnswer.index0f(letter) >= 0;    \\declaring a seperate boolean variable
    if (isHit) {                      \\ these four lines are just conditional instructions, they do not 
      mHits += letter;           \\ return anything to applyGuess(char letter)?
    } else {
      mMisses += letter;
    }

For comparison here is a similar boolean method but with a return statement

 public boolean dispense() {
   boolean wasDispensed = false;
     if (!isEmpty()) {
      mPEZCount--;
      wasDispensed = true;
    }

    return wasDispensed;
    }

The code above to me, makes sense because it return the value of "wasDispensed" to "dispense()", which is why it was declared a boolean in the first place. Please explain like I'm five as to what the differences are. Thanks in advance :)

2 Answers

Kourosh Raeen
Kourosh Raeen
23,732 Points

There is a return statement. Here's the code:

public boolean applyGuess(char letter) {
    boolean isHit = mAnswer.indexOf(letter) >= 0;
    if (isHit) {
        mHits += letter;
    } else {
        mMisses += letter;
    }            
    return isHit;
}
Kshatriiya .
Kshatriiya .
1,464 Points

Ops, that was very silly of me, thank you for point it out :)

Kourosh Raeen
Kourosh Raeen
23,732 Points

No worries! Happy coding!