为了生成像TRUE或FALSE这样的随机布尔值,首先创建一个新的Random对象-
Random randNum = new Random();
现在,循环遍历所需的布尔值,并使用nextBooleans()
方法−生成随机布尔值-
for (int i = 1; i <= 5; ++i) { booleanrandomRes = randNum.nextBoolean(); System.out.println(randomRes); }
import java.util.Random; public class Demo { public static final void main(String... args) { Random randNum = new Random(); System.out.println("Displaying random Booleans..."); for (int i = 1; i <= 5; ++i) { boolean randomRes = randNum.nextBoolean(); System.out.println(randomRes); } } }
输出结果
Displaying random Booleans... true false false true true
让我们再次运行它以获得独特的随机布尔-
Displaying random Booleans... false false true true false