Java Java Objects Harnessing the Power of Objects Throwing Exceptions

Vikrant Bhosale
PRO
Vikrant Bhosale
Pro Student 2,680 Points

Exception handling query

Question: Add logic to the drive method so that it throws an IllegalArgumentException if there aren't enough bars to support the laps request. Remember it takes 1 bar of energy to go around a lap. I have added this code from line 31. Please tell my what's wrong.

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 int charge() {
    barCount = MAX_BARS;
    return barCount;
  }

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

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

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

  public void drive(int laps) {

    if (laps>MAX_BARS)
    {
      throw new IllegalArgumentException ("lapsset are more than the capacity of the battery");
    }
    //lapsDriven += laps;
   // barCount -= laps;
  }
}

2 Answers

Yanuar Prakoso
Yanuar Prakoso
14,816 Points

Hi Vikrant

First of all the if statement should be if(laps > barCount) we use barCount instead of MAX_BAR constant because the GoKart is not always in fully charged condition.

Second of all please uncomment the //lapsDriven += laps; and //barCount -= laps; code because you will need it.

I hope this can help a little

Vikrant Bhosale
Vikrant Bhosale
Pro Student 2,680 Points

But in the following method public int charge() { barCount = MAX_BARS; return barCount; }

barCount = MAX_BARS. So what is the benefit of using barCount over MAX_BARS.

Yanuar Prakoso
Yanuar Prakoso
14,816 Points

barCount will be = MAX_BAR only when you or the user call the method charge() after that as long as you call the drive() method the barCount will be decremented one by one according to how much lap you want to pass into the drive(laps) method. If your GoKart is already being used before and the next user does not call the charge() method then barCount will not equal MAX_BAR.

Yes you can pass this test using Manish Giri's way but I really think it does not suit the challenge. If (laps - MAX_BAR < 0) meaning MAX_BAR is larger than laps. Thus the laps you requested is smaller than MAX_BAR. Let's use your logic if barCount is = MAX_BAR will it be okay if laps is not as much as MAX_BAR? will it should still able to run the GoKart?

But then again if you just want to pass the challenge it does not matter. I just see it as strange and missed the point of the challenge that's all.

Manish Giri
Manish Giri
16,264 Points

I think the condition should be if (laps - MAX_BARS < 0).