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 trialKyle Dudley
604 Pointshow?
idk
class GoKart {
public static final int MAX_BARS = 8;
private String color;
private int barCount;
private int lapsDriven;
private int laps;
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() {
lapsDriven++;
barCount--;
laps == 6;
}
}
2 Answers
Amrit Pandey
17,595 PointsIt's simple.
You see, our people say that, the program we created only allows them to drive their car for just one LAP.
They need more laps. Now closely see this drive
function.
public void drive() {
lapsDriven++;
barCount--;
}
When you power up your vehicle to make a lap, you will use drive() method to complete one lap. Then you will use drive() method to complete second lap. You will keep calling this method for n times for n number of laps.
How, about we specify this method to run our car for n times without calling it n times. Smart is'nt it?
So we pass a parameter
which will be our lap number and, keep executing the method untill we complete the specified number of laps.
public void drive(int laps) {
while(laps>lapsDriven){
lapsDriven++;
barCount--;
}
}
I hope you understood the concept. :)
Amrit Pandey
17,595 Pointssethkroger Yeah I understand that. lapsDriven
is declared as global variable. Whatever value we increment is stored in lapsDriven
the drive
method should be somewhat like this.
public void drive(int laps){
int lapsOver;
while(laps>lapsOver && this.isBatteryEmpty()){
lapsOver+=1;
barCount-=1;
}
}
I am still starting, so take this as a pseudo code.
Seth Kroger
56,413 PointsSeth Kroger
56,413 PointsThere's a rather serious logic error in that. What happens when you've already driven some laps and want to drive more? (lapsDriven is not zero)
Amrit Pandey
17,595 PointsAmrit Pandey
17,595 PointsCan't We just initialize lapsDriven?
Seth Kroger
56,413 PointsSeth Kroger
56,413 PointsYou can initialize it in the constructor but you'll still have the same issue. lapsDriven is supposed to be a record of the laps. If you drive(4) laps and then drive(2) you should have 6 lapsDriven and still be able to drive more.
Kyle Dudley
604 PointsKyle Dudley
604 PointsThanks for the answer!