A. Hodges A. Hodges - 23 days ago 12
Java Question

Throwing Illegal Argument Exception

I'm not understanding why my compiler is showing an illegal argument exception when the argument is valid. Any ideas?

public class bikeBrakeTest {
public enum BrakeType {Caliper, Cantilever, LinearPull, Disc };
public BrakeType brakes;

public bikeBrakeTest() //Defualt Constructor
{
brakes = BrakeType.Caliper;
}

public bikeBrakeTest(BrakeType aBrake) //Parameterized Constructor
{
setBrakes(aBrake);
}


public void setBrakes (BrakeType aBrake) //Mutator Method "set"
{
if (aBrake.equals("Caliper") || aBrake.equals("Cantilever") || aBrake.equals("LinearPull") || aBrake.equals("Disc"))
{
brakes = aBrake;
}
else throw new IllegalArgumentException("invalid");
}
}


And then my tester is..

public class testing {
public static void main(String[] args)
{
bikeBrakeTest myBike = new bikeBrakeTest();
myBike.setBrakes(bikeBrakeTest.BrakeType.Caliper);
}
}

Answer

You can't directly compare enum to string 'Caliper', rather you need to use aBrake == BrakeType.Caliper for comparison as shown below.

public void setBrakes (BrakeType aBrake) {
       if (aBrake == BrakeType.Caliper || 
          aBrake == BrakeType.Cantilever || 
          aBrake == BrakeType.LinearPull || 
          aBrake == BrakeType.Disc) {
                  brakes = aBrake;
        } 
       else throw new IllegalArgumentException("invalid");
 }