Java Java Objects Harnessing the Power of Objects Throwing Exceptions

Mehtab Kayani
Mehtab Kayani
3,179 Points

I need some help...

I dont understand why its not working ?

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;
    int newLaps = barCount + laps;
    if(newLaps > MAX_BARS){
        throw new IllegalArgumentException("Too many laps!!");
    }
    barCount = newLaps;
  }
}

2 Answers

Tabatha Trahan
Tabatha Trahan
17,690 Points

Within the drive method, you'll want to check to see if the laps passed in as an argument plus your current lapsDriven variable is greater than your current barCount. If it is, you'll want to throw the exception. If it isn't, you'll want to move on and increment lapsDriven and decrement your barCount.

public void drive(int laps) {
    if(laps + lapsDriven > barCount){
      throw new IllegalArgumentException("Not enough bars");
    }
    lapsDriven += laps;
    barCount -= laps;
  }