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 trialDaniel Schwemmlein
4,960 Pointsstuck again at a java challenge
Hey! Once again I'm stuck here. This time I'm supposed to code that my go kart can't drive another lap on that battery level. I guess I'm close because I'm no longer getting compiler errors. Could someone please point out what I'm doing wrong still. Thanks in advance!
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 drive() {
drive(1);
}
public void drive(int laps) {
// Other driving code omitted for clarity purposes
mBarsCount -= laps;
int newBarsCount = mBarsCount - laps;
if (newBarsCount < 1) {
throw new IllegalArgumentException("Not enough battery remains");
}
}
public void charge() {
while (!isFullyCharged()) {
mBarsCount++;
}
}
public boolean isBatteryEmpty() {
return mBarsCount == 0;
}
public boolean isFullyCharged() {
return mBarsCount == MAX_BARS;
}
}
3 Answers
Allan Clark
10,810 PointsThe -= operator subtracts then sets the variable to the new value. mBarsCount -= laps; //is the same as mBarsCount = mBarsCount - laps;
So your code is subtracting laps from mBarsCount twice. mBarsCount -= laps;
int newBarsCount = mBarsCount - laps;
and then setting a newBarsCount to that value.
Hope this helps
Dan Johnson
40,533 PointsYou'll want to change the state of the object (the value of mBarsCount) after the check that could result in an exception. That way if result is something invalid (a negative value) it won't be stored.
Nicolas Hampton
44,638 PointsActually, since we're writing the code so the mBarsCount never goes below 0, and we're using integers, the if test could use the isBatteryEmpty method, which returns the boolean result we need in the if loop. Remember, don't repeat yourself, keep it DRY!
Allan Clark
10,810 PointsAllan Clark
10,810 PointsI borked the formatting and can't seem to figure it out at the moment. TL:DR you subtracted laps twice
Craig Dennis
Treehouse TeacherCraig Dennis
Treehouse TeacherHey Alan,
Three backticks followed by the word java and then surround your code..
givesYouVeryPrettyColor("coding");
Allan Clark
10,810 PointsAllan Clark
10,810 PointsWunderbar! ty kind sir!