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 trializqcabvvli
4,111 PointsUnable to solve!
Please help!! Also explain the reason for the answer.
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.
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
Bunyod Kh
10,221 PointsThis method - isFullyCharged() - is used to identify whether a Kart is fully charged or not. It returns [true - if it is fully charged] or [false - if it is not].
We are using isFullyCharged() inside the charge() - method, because we should know the state of the batteries before charge the batteries. And isFullyCharged() gives us the state of the battery -> full or not.
In this case, isFullyCharged() is helper method, but you surely may not use it in your own projects. However, using helper methods is good way to manage your code.
Code:
public void charge()
{
while(!isFullyCharged()) //while the batteries are not fully charged
{
mBarsCount++; //charge them
}
}
Here: !isFullyCharged() - we are calling this method with the operator (! - "is not"). So, we can read it : while isFullyCharged() is not returning "true" continue charging by incrementing mBarsCount using operator (++ -"increment").
p.s. You can rewrite the code like this if you don't like helper method:
public void charge() {
while(!(mBarsCount == MAX_ENERGY_BARS)){
mBarsCount++;
}
}
anil rahman
7,786 Pointspublic void charge() {
while(!isFullyCharged()){
mBarsCount++;
}
}