gpt4 book ai didi

Java 老虎机类

转载 作者:行者123 更新时间:2023-12-01 14:55:10 26 4
gpt4 key购买 nike

我正在编写一个老虎机类,它生成 3 个由 3 个随机数组成的数组,并检查所有数字是否匹配,如果匹配,则宣布它们获胜。我编写了另一个程序来运行 1000 台老虎机并计算获胜者。我面临的问题是它总是给我 0 个获胜者。有什么帮助吗?以下是每个的代码:

老虎机类

import java.util.*;

public class SlotMachine{

private int[] row1 = new int[3];
private int[] row2 = new int[3];
private int[] row3 = new int[3];

public SlotMachine() {
playMachine();
}

public void playMachine() {

Random rand = new Random();

for (int counter = 0; counter < 3; counter++) {
row1[counter] = rand.nextInt(10);
}

for (int counter = 0; counter < 3; counter++) {
row2[counter] = rand.nextInt(10);
}

for (int counter = 0; counter < 3; counter++) {
row3[counter] = rand.nextInt(10);
}
}

public boolean isWinner() {

if (row1[0] == row1[1]) {
if (row1[0] == row1[2]) {
return true;
}
}

if (row2[0] == row2[1]) {
if (row2[0] == row2[2]) {
return true;
}
}

if (row3[0] == row3[1]) {
if (row3[0] == row3[2]) {
return true;
}
}

return false;
}
}

获胜计数器:

import java.util.*;

public class Play1000SlotMachines {

public static void main(String[] args) {
SlotMachine slotMachine = new SlotMachine();
int count = 0;

for (int i = 0; i < 1000; i++) {
if (slotMachine.isWinner() == true) {
count = count + 1;
}
}

System.out.println("From 1000 slot machines, " + count + " were winners.");
}
}

最佳答案

您永远不会重新滚动老虎机。我还更改了该方法的名称,以反射(reflect)此实现。如果您想玩 1000 台不同的老虎机,请将新老虎机的声明移至 for 循环中。这将创建老虎机类的 1000 个不同实例,而不是下面的实现,其中创建老虎机的单个实例,然后玩 1000 次。一个重要的区别。

public class PlaySlotMachine1000Times {
public static void main(String[] args) {

SlotMachine slotMachine = new SlotMachine();
int count = 0;

for (int i = 0; i < 1000; i++) {
slotMachine.playMachine();
if (slotMachine.isWinner())
count++;
}
System.out.println("From 1000 slot machines, " + count + " were winners.");
}
}

关于Java 老虎机类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14371252/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com