随机抽一个数,奇数偶数概率各占二分之一,即为硬币正反面概率。所以使用Random类随机抽取一个数,再确认是奇还是偶,从而得到题目所要求的结果。
package cointoss;
import java.util.Random;public class CoinToss {
public static void main(String[] args) {
Random rand = new Random();
int coin = rand.nextInt();
if(coin % 2 == 0)
System.out.println("heads");
else
System.out.println("tails");}
}