我被分配创建一个模拟抛硬币的方法。我认为我这里的代码非常可靠,只是我无法让它在 n 次翻转后显示一系列结果。因此,我只得到 H 或 T,而不是显示 HTHHHTTTHTT。
public static void main(String[] args) {
System.out.println((flipCoin(2, 10)));
}
public static String flipCoin(int chance, int numFlips) {
String result = "";
Random rando = new Random();
chance = rando.nextInt();
for (int i = 0; i < numFlips; i++) {
if (chance % 2 == 0) {
result = "H";
}
else {
result = "T";
}
numFlips++;
}
return result;
}
最佳答案
您迭代 numFlips
次,但在每次迭代中,您调用 result = "H";
或result = "T";
。这设置了 result
的值到 "H"
或"T"
.
相反,您应该附加它。您可以通过调用result += "T";
来做到这一点,或者您可以使用StringBuilder
并调用stringBuilder.append("T");
.
关于java - 抛硬币方法建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60012573/