[Java] 随机返回1或0

Introduction to Java Programming 上的一道习题 3.16

Write an expression that returns 0 or 1 randomly.

((int)(10 * Math.random())) % 2  

或者用另一种方法:

import java.util.Random;
public class TestClass {
    public static void main(String[] args) {
        Random random = new Random(3);
        System.out.print("\nFrom random: ");
        for (int i = 0; i < 10; i++)
            System.out.println(random.nextBoolean() ? 1 : 0);
    }
}

猜你喜欢

转载自blog.csdn.net/ftell/article/details/82225163