我有一个班级“班车”,有4个布尔人:
class Car {
boolean mWheel1 = true
boolean mWheel2 = true
boolean mWheel3 = true
boolean mWheel4 = true
}
我还有一个方法“void 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语句或静态解决方案。
答案 0 :(得分: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;
}
答案 1 :(得分: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;
}
}
答案 2 :(得分:1)
是的,在这个简单的例子中,你想要为你的车轮使用一个数组或集合。但是,按名称动态访问属性可能有合理的理由,您可以使用反射API执行此操作:
void removeWheel(int wheelNum) throws Exception {
Car.class.getDeclaredField("mWheel" + wheelNum).setBoolean(this, false);
}
答案 3 :(得分: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;
}
}