2016-11-14 87 views
0

我不明白爲什麼我的編譯器在參數有效時顯示非法參數異常。有任何想法嗎?拋出非法參數異常

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

1.它不是編譯器。 2.爲什麼你認爲'BrakeType'永遠等於'String'? –

+1

「aBreak」不等於「Caliper」。不過,它可能等於'BrakeType.Caliper'。 –

回答

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

非常感謝! –