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 trialZachary Martin
3,545 PointsNot enough battery
I looked though other threads and I still couldn't figure out the answer.
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;
if (mBarsCount < 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;
}
}
4 Answers
Ilya Dolgirev
35,375 PointsWell, before modify mBarsCount you have to be sure that you have enough battery level to substract requested number of laps. So, if your battery level is lower than requested laps the condition will be executed and throw an exception. If your battery is enough to drive requested laps so it passed through condition without throwing an exception directly to next line of code after the condition - modifying the mBarsCount.
Ilya Dolgirev
35,375 PointsThe idea is simple - you have to compare you remaining battery level with requested laps to drive. So, the following code should work:
public void drive(int laps) {
if (mBarsCount < laps) {
throw new IllegalArgumentException("Not enough battery remains");
} // If battery level is more than requested lap this code block won't be executed.
mBarsCount -= laps;
}
Zachary Martin
3,545 Pointsit worked after I put the if throw park above mBarsCount -= laps
I still don't understand why it had to be in that particular sequence.
Ilya Dolgirev
35,375 PointsThis answer is very descriptive :) Look at my implementation. I modify mBarsCount after the conditional.
Zachary Martin
3,545 PointsLol yeah I missed the part where you changed how you ordered it inside the block, but I don't quite grasp the importance of orienting it that way. I thought if I just stuck it in there with the right variables it would work.
Zachary Martin
3,545 PointsZachary Martin
3,545 PointsThat makes sense but it was oriented differently in the Pez Dispenser video, sorry if I ask to many questions but the subtle nuances help making coding intuitive for me