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 trialAdrian Bosada
749 PointsLearn Java>Objects>Exceptions>Quiz help!!!
I am getting this question wrong, but it says I need to throw the exception before I change the barCount and lapsDriven fields. I did, didn't I?
class GoKart {
public static final int MAX_BARS = 8;
private String color;
private int barCount;
private int lapsDriven;
public GoKart(String color) {
this.color = color;
}
public String getColor() {
return color;
}
public void charge() {
barCount = MAX_BARS;
}
public boolean isBatteryEmpty() {
return barCount == 0;
}
public boolean isFullyCharged() {
return MAX_BARS == barCount;
}
public void drive() {
drive(1);
}
public void drive(int laps) {
int newBarCount = barCount -= laps;
if (newBarCount < 1) {
throw new IllegalArgumentException("Not enough battery bars!");
}
barCount = newBarCount;
lapsDriven += laps;
}
}
2 Answers
Jennifer Nordell
Treehouse TeacherHi there! Actually no, you change barCount before you throw the exception in this line:
int newBarCount = barCount -= laps;
Remember that the -=
will take barCount minus laps and assign it back into barCount thus changing the value. However, I'd like to give some hints here on how to solve this and we'll see if you can get it from there.
- There is no need to create a new variable.
newBarCount
can and should be removed. - Check to see if laps is greater than the bar count
- If it is, throw an exception
- The rest of the code should remain unchanged.
- The code you add to this challenge should only contain an if statement with a block containing one line that throws a new IllegalArgumentException
Good luck, but let me know if you're still stuck!
adil rafaa
3,194 PointsFirst you don't need to create new variable newBarCount , and then you can just check if ( barCount > = 0) then throw an exception ! good luck