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 trialAdiv Abramson
6,919 PointsCompiler 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!
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
Full Stack JavaScript Techdegree Graduate 35,467 PointsHey 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.
Craig Dennis
Treehouse TeacherWhy use the ternary statement and not just return the expression?
return mBarsCount == 0;
Adiv Abramson
6,919 PointsWow, your solution is even more compact! Thank you!
Adiv Abramson
6,919 PointsAdiv Abramson
6,919 PointsThank you so much. I was unaware of this restriction on the use of the ternary operator but now I know!