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) Harnessing the Power of Objects Helper Methods

Compiler error using ternary operator in Java

I originally wrote the code using full if statements but thought it would be more compact (and cooler!) to use the ternary operator. However the task editor says "No bueno!" Can anyone tell me where I went wrong? Thanks!

GoKart.java
public class GoKart {
  public static final int MAX_BARS = 8;
  private String mColor;
  private int mBarsCount;

  public GoKart(String color) {
    mColor = color;
    mBarsCount = 0;
  }

  public String getColor() {
    return mColor;
  }

  public void charge() {
    mBarsCount = MAX_BARS;
  }

  public boolean isBatteryEmpty(){
    return (mBarsCount == 0) ? true : false;
  }// isBatteryEmpty()

  public isFullyCharged() {
    return (mBarsCount == MAX_BARS) ? true : false;
  }// isFullyCharged

}

2 Answers

Rob Bridges
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Rob Bridges
Full Stack JavaScript Techdegree Graduate 35,467 Points

Hey there Adiv,

As usual you are super close on this. However with ternary syntax remember a variable needs to be given to assign the value to. I've done one for isFullyCharged() for you below

public boolean isFullyCharged() { 
   boolean  isCharged = (mBarsCount == MAX_BARS) ? true : false; 
   Return isCharged;
} 

As powerful as ternary statements are they can only assign values to a variable and not return them directly.

With that being said I'm going to let you do the second for the isBatteryEmpty() method.

Shout if you need any help!

Thanks.

Thank you so much. I was unaware of this restriction on the use of the ternary operator but now I know!

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

Why use the ternary statement and not just return the expression?

return mBarsCount == 0;

Wow, your solution is even more compact! Thank you!