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

Gabriel Favela
Gabriel Favela
1,565 Points

IllegalArgumentException troubles...

Hi, I am having quite a bit of trouble with this, I am trying to throw a new IllegalArgumentException if the number of laps driven by the kart is greater than the battery can handle to say that there is no more battery left. Maybe my syntax is wrong so could someone help me out please? just starting out.

GoKart.java
class GoKart {
  public static final int MAX_BARS = 8;
  private String color;
  private int barCount;
  private int lapsDriven;

  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;
  }

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

  public void drive(int laps) {
    lapsDriven += laps;
    barCount -= laps;
    if (lapsDriven > barCount) {
      throw new IllegalArgumentException("no more battery");
    }

  }


}

2 Answers

andren
andren
28,558 Points

Your syntax is fine, but there are two issues related to what the task asks for:

  1. You are meant to throw the exception before you modify the lapsDriven and barCount variables. So your if check should be placed at the top of the method, not at the bottom.

  2. You have misunderstood the task a bit. You are not meant to throw an exception when the car has driven more laps than it's battery count. You are meant to throw an exception if the requested lap count (the laps parameter) is higher than the battery count.

If you fix those two issues like this:

public void drive(int laps) {
    if (laps > barCount) { // Moved to top and changed lapsDriven to laps
      throw new IllegalArgumentException("no more battery");
    }
    lapsDriven += laps;
    barCount -= laps;
}

Then your code will work.

basically you put the task above the check.if.this.will.endanger.my.task.

like putting a warning lable at the bottom of the inside of a cup. "dont drink this, its poison!"

public void drive(int laps) {
    if (lapsDriven > barCount) {
      throw new IllegalArgumentException("no more battery");
    }
    lapsDriven += laps;
    barCount -= laps;
  }