Java程序抛硬币
假设我们有一个硬币和10个机会。在这里,我们将首先初始化头,尾和机会的值-
int heads = 0;int tails = 0;
int chances = 10;
现在,我们将使用Random对象获得head和tail值-
for (int i = 1; i<= chances; i++) {if (t.chanceFunc().equals("tails")) {
tails++;
} else {
heads++;
}
}
上面的函数chanceFunc()
具有使用nextInt()
方法获取下一个随机值的Random类。检查条件并返回头和尾的值-
public String chanceFunc() {Random r = new Random();
int chance = r.nextInt(2);
if (chance == 1) {
return"tails";
} else {
return"heads";
}
}
示例
import java.util.Random;class Toss {
public String chanceFunc() {
Random r = new Random();
int chance = r.nextInt(2);
if (chance == 1) {
return"tails";
} else {
return"heads";
}
}
}
public class Demo {
public static void main(String[] args) {
Toss t = new Toss();
int heads = 0;
int tails = 0;
int chances = 10;
for (int i = 1; i<= chances; i++) {
if (t.chanceFunc().equals("tails")) {
tails++;
} else {
heads++;
}
}
System.out.println("Chances = " + chances);
System.out.println("Heads: " + heads);
System.out.println("Tails: " + tails);
}
}
输出结果
Chances = 10Heads: 3
Tails: 7
让我们再次运行程序-
Chances = 10Heads: 4
Tails: 6
以上是 Java程序抛硬币 的全部内容, 来源链接: utcz.com/z/357175.html