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 trial

Java Java Objects Harnessing the Power of Objects Increment and Decrement

kabirdas
kabirdas
1,976 Points

How 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

GoKart.java
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

Hi 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.

That'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
kabirdas
1,976 Points

Ohhh 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?

You need two plus signs; lapsDriven++;.

kabirdas
kabirdas
1,976 Points

OHH. why is two needed if I only need to increment once?

kabirdas
kabirdas
1,976 Points

Ok 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.