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 (Retired) Harnessing the Power of Objects Incrementing

Need to speed it up

Hello my code seems to be correct in this instance but when I attempt to run the code it takes a bit and then tells me the program took too long to run could anyone help me try to speed this up a bit?

GoKart.java
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() {
    while(!isFullyCharged()){
    mBarsCount = mBarsCount++;
    }
  }

  public boolean isBatteryEmpty() {
    return mBarsCount == 0;
  }

  public boolean isFullyCharged() {
    return mBarsCount == MAX_ENERGY_BARS;
  }

}

3 Answers

Seth Kroger
Seth Kroger
56,413 Points

The "Taking too long" message usually means you have in infinite loop going on.

The line to increment the bars should just be "mBarsCount++;" The increment/decrement operators already include assignment and can have bizarre side-effects if you put an explicit assignment in.

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

The infinite loop is because incrementing returns the value before the increment, so you are incrementing the value and then immediately setting it back to what it was. Whoops! Seth Kroger is correct, by just putting it on a line by its own.

See it's dangerous ;)

thank you for the responses they seem to have removed the loop and ty for the clarification on what it was saying