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) 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,733 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,733 Points

No worries! Happy coding!