2013-10-15 19 views
0

我有一個類「類汽車」與4個布爾值:Java:如何根據輸入引用類var?

class Car { 
    boolean mWheel1 = true 
    boolean mWheel2 = true 
    boolean mWheel3 = true 
    boolean mWheel4 = true 
} 

我也有一種方法「空隙removeWheel」我只通過1個參數,車輪數:

void removeWheel(int wheelNum) { 
    // I need help with the following line 
    Car.mWheel(wheelNum) = false 
} 

最後線是我需要幫助的。當我僅將一個數字(1,2,3,4)傳遞給我的刪除輪方法時,如何才能在Car類中引用正確的「Car.mWheel」數字變量?請注意,我可能會將100多個車輪添加到我的汽車中,所以我想動態連接對「Car.mWheel(wheelNum)」的引用,而不是做一些if語句或靜態解決方案。

+1

與if/else語句...或創建陣列,這是好多了。 – libik

+0

'switch'是另一種可能性。 鏈接:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html – bbalchev

+2

這個例子尖叫「數組!使用數組!!」 – dasblinkenlight

回答

1

這是階級如何看:

public class Car { 

    private boolean[] wheels = new boolean[4]; 

    public Car() { 
     for (int i = 0; i < 4; i++) { 
      wheels[i] = true; 
     } 

    } 

    public void removeWheel(int wheelNum) { 
     getWheels()[wheelNum] = false; 
    } 

    /** 
    * @return the wheels 
    */ 
    public boolean[] getWheels() { 
     return wheels; 
    } 

    /** 
    * @param wheels the wheels to set 
    */ 
    public void setWheels(boolean[] wheels) { 
     this.wheels = wheels; 
    } 
} 
+0

我認爲這個答案是最接近OP要求的。 – bbalchev

4

而不是

class Car { 
    boolean mWheel1 = true 
    boolean mWheel2 = true 
    boolean mWheel3 = true 
    boolean mWheel4 = true 
} 

void removeWheel(int wheelNum) { 
    // I need help with the following line 
    Car.mWheel(wheelNum) = false 
} 

class Car { 
    boolean mWheel[4] = {true, true, true, true}; 
} 

void removeWheel(int wheelNum) { 
    mWheel[wheelNum] = false; 
} 
0

上述陣列是最好的選擇,但如果你想這樣做無需更改屬性:

void removeWheel(int wheelNum) { 
    switch (wheelNum) { 
     case 1: 
      mWheel1 = false; 
      break; 
     case 2: 
      mWheel2 = false; 
      break; 
     case 3: 
      mWheel3 = false; 
      break; 
     case 4: 
      mWheel4 = false; 
      break; 
     default: 
      break; 
    } 
} 
1

是的,在這個微不足道的例子中,你想爲你的車輪使用一個數組或集合。但有一點是按名稱動態地訪問屬性正當理由的,你可以這樣做,使用反射API:

void removeWheel(int wheelNum) throws Exception { 
    Car.class.getDeclaredField("mWheel" + wheelNum).setBoolean(this, false); 
}