在Java中,如果一个布尔值为true,则其他所有其他都变为false

时间:2016-01-11 17:06:26

标签: java

我想知道在Java中是否有可能有一系列布尔值,例如:

    boolean boo1, boo2, boo3, boo4, boo5;

我想这样做,以便如果其中一个布尔变为真,那么其他所有人都会变得虚假。我知道这可以通过一系列long if语句来完成,但有一种更简单的方法可以实现这一点。

谢谢!

1 个答案:

答案 0 :(得分:1)

使用数组

boolean bs = new boolean[10];
lightUp(bs, 6); // only bs[6] will be true after this
lightUp(bs, 0); // only bs[0] will be true after this

将lightUp函数定义为:

/**
 * modifies the passed-in array to make sure only
 * the selected index is set to true
 */
void lightUp(boolean[] bs, int index) {
   for (int i=0; i<bs.length; i++) bs[i] = false;
   bs[index] = true;
}
相关问题