抛出非法论据例外

时间:2016-11-14 23:56:56

标签: java class

我不明白为什么我的编译器在参数有效时显示非法参数异常。有什么想法吗?

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

然后我的测试员就是......

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

1 个答案:

答案 0 :(得分:1)

您无法直接将enumstring 'Caliper'进行比较,而是需要使用aBrake == BrakeType.Caliper进行比较,如下所示。

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