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 Throwing Exceptions

Avery Freeman-wheaton
Avery Freeman-wheaton
2,273 Points

Trouble with throw new IllegalArgumentException in GoKart exercise

Hi,

I seem to be having trouble now with the

throw new IllegalArgumentException("Not enough battery remains");

Here's my codeblock I tried, but can't get to work:

   public void drive(int laps) {
    // Other driving code omitted for clarity purposes
    mBarsCount -= laps;
    int newLapsLeft = mBarsCount - laps;
    if (newLapsLeft > MAX_BARS) {
     throw new IllegalArgumentException("Not enough battery remains");
    }
    mBarsAmount = newLapsLeft;
  }

Not really sure how to do this. I tried to put it in as similarly as the demonstration showed, but I just don't seem to be able to get it.

Thanks! -Avery

GoKart.java
public class GoKart {
  public static final int MAX_BARS = 8;
  private String mColor;
  private int mBarsCount;

  public GoKart(String color) {
    mColor = color;
    mBarsCount = 0;
  }

  public String getColor() {
    return mColor;
  }

   public void drive(int laps) {
    // Other driving code omitted for clarity purposes
    mBarsCount -= laps;
    int newLapsLeft = mBarsCount - laps;
    if (newLapsLeft > MAX_BARS) {
     throw new IllegalArgumentException("Not enough battery remains");
    }
    mBarsAmount = newLapsLeft;
  }

   public void drive() {
    drive(1); 
  }



  public void charge() {
    while (!isFullyCharged()) {
      mBarsCount++;
    }
  }

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

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

}

1 Answer

Take notice of these two lines of code:

mBarsCount -= laps;
int newLapsLeft = mBarsCount - laps;

You are substracting the laps twice!

That being said, you are overthinking it. All you need to do is check if it can be done:

public void drive(int laps) {
    // Other driving code omitted for clarity purposes
    if(mBarsCount <= laps) throw new IllegalArgumentException("Not enough battery remains");
    else mBarsCount -= laps;
  }
Avery Freeman-wheaton
Avery Freeman-wheaton
2,273 Points

Thank you! That really helped!

I really appreciate the help in these forums. Sorry it took me so long to reply. Have a nice day!