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 trialMatt Kuzovkin
1,653 PointsI can not come up with a solution according to the task description, can you help me out please. Thank you!
My code
public class GoKart {
public static final int MAX_ENERGY_BARS = 8;
private String mColor;
private int mBarsCount;
public GoKart(String color) {
mColor = color;
mBarsCount = 0;
}
public String getColor() {
return mColor;
}
public void charge() {
mBarsCount = MAX_ENERGY_BARS;
}
public boolean isBatteryEmpty() {
return mBarsCount == 0;
}
public boolean isFullyCharged() {
return mBarsCount == MAX_ENERGY_BARS;
}
}
2 Answers
Andrews Gyamfi
Courses Plus Student 15,658 PointsHi Matt, the question states: "Okay, so let's use our new isFullyCharged helper method to change our implementation details of the charge method. Let's make it so it will only charge until the battery reports being fully charged. Let's use the ! symbol and a while loop. Inside the loop increment mBarsCount."
We create helper methods to reduce code complexity, improve code development, testing and refactoring. Here is a breakdown of the isFullyCharged method:
public boolean isFullyCharged() {
return mBarsCount == MAX_ENERGY_BARS;
}
- The isFullyCharged helper method has a boolean return type i.e. it returns a true or false value.
- The method checks whether the current number of battery bars (represented by the variable "mBarsCount") is equal to the maximum (represented by the constant "MAX_ENERGY_BARS"), then it returns the result. A very basic way of rewriting:
return mBarsCount == MAX_ENERGY_BARS;
would be:
if(mBarsCount == MAX_ENERGY_BARS){
return true;
}else{
return false}
The question is asking us to use the 'isFullyCharged' method to 'help' the 'charge' method to perform its function. Below is the solution as per the question's requirement:
public void charge() {
while(!isFullyCharged()){
mBarsCount++;
}
}
I hope this helps! I'm happy to explain more if required.
Cheers!
Matt Kuzovkin
1,653 PointsThank you!
Steve Hunter
57,712 PointsSteve Hunter
57,712 PointsGood answer! Covers the question well.
One tip - if you type java (or whatever language you're using) immediately after the opening three backticks, it'll format your code a little nicer.
I've done that to your
charge()
method by way of demonstration. It adds the colours rather than the grey text that's a little difficult to read.Steve.