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 trialWillie Suggs
Courses Plus Student 5,879 Pointsany understanding you can give would be nice!
i follow along in videos, i take notes, i copy the code straight from the video but once i try to apply it, it seem like i can't figure the correct why to write it. Not only do i need help with this current issue, but i need advise on what am i losing from the video to my exercise & what do you advise me to do to get better beyond what I'm already doing...thanks from the rookie :)
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);
if (drive() > mBarsCount) {
throw new IllegalArgumentException("Not enough battery remains");
}
}
public void drive(int laps) {
// Other driving code omitted for clarity purposes
mBarsCount -= laps;
}
public void charge() {
while (!isFullyCharged()) {
mBarsCount++;
}
}
public boolean isBatteryEmpty() {
return mBarsCount == 0;
}
public boolean isFullyCharged() {
return mBarsCount == MAX_BARS;
}
}
1 Answer
Seth Kroger
56,414 PointsYou have drive calling itself, which will result in an infinite recursion. Because you have two drive methods and the drive() with no arguments calls the drive(int) method straight away, the exception throwing code should go in the drive(int methmBarsod). Then in the drive(int) method, you need to check if laps is greater than mBarsCount and throw the exception.
Willie Suggs
Courses Plus Student 5,879 PointsWillie Suggs
Courses Plus Student 5,879 Pointspublic drive (int laps) { mBarsCount -= laps; if (mBarsCount < laps) { throw new IllegalArgumentException("not enough battery remains); }
what am i doing wrong?
Seth Kroger
56,414 PointsSeth Kroger
56,414 PointsWhen you're checking to see if there'll be a problem, it's better to check before the problem than after it. Here the problem is deducting more battery charge than is available, so you need to check the amount of battery before you deduct it not after.