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 trialkabirdas
1,976 PointsHow to increment
In the video lesson prior, we used to jshell to increment and decrement, and I'm not sure how that translates to being used outside the shell.
I know the shorthand is either: +=
or
++
but I can't seem to figure out how it's to be coded.
Can someone provide some insight?
Thanks
class GoKart {
public static final int MAX_BARS = 8;
private String color;
private int barCount;
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;
}
private int lapsDriven;
}
5 Answers
Steve Hunter
57,712 PointsHi Kabir,
Declare your new lapsDriven
member variable at the top of the class along with the others.
Then, you want to create a method that is public, returns nothing (void
) and increments the new member variable using ++
or += 1
.
That all looks like:
public void drive(){
lapsDriven++;
// could be
// lapsDriven += 1;
}
I hope that helps,
Steve.
Steve Hunter
57,712 PointsThat's how it works in many languages, not just Java.
You can add to a variable by doing:
int aValue = 0;
aValue++; // adds one
aValue += 1; // adds one
aValue + 2; // adds two
aValue += 2; // adds two
aValue + 27; // guess what ...
Steve.
kabirdas
1,976 PointsOhhh I see now. Wow Thanks!
However, when I try that code, I get an error message saying task 1 is no longer passing:
public void drive() {
lapsDriven+;
} ```
As I need to increment it by one. I'm not sure what's wrong?
Steve Hunter
57,712 PointsYou need two plus signs; lapsDriven++;
.
kabirdas
1,976 PointsOHH. why is two needed if I only need to increment once?
kabirdas
1,976 PointsOk great, thanks so much! I saw that in the lesson and wrote it down for my notes, but I wasn't sure why that was.