[英]Coin flip method advice
I was assigned to create a method that simulates flipping a coin.我被指派创建一种模拟抛硬币的方法。 I think my code here is pretty solid, only I can't get it to show a series of results after n number of flips.我认为我这里的代码非常可靠,只是在 n 次翻转后我无法让它显示一系列结果。 So instead of showing HTHHHTTTHTT, I'm only getting H or T.因此,我没有显示 HTHHHTTTHTT,而是只显示 H 或 T。
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;
}
You iterate over numFlips
times, but in each iteration, you call either result = "H";
您迭代numFlips
次,但在每次迭代中,您都调用result = "H";
or result = "T";
或result = "T";
. . This sets the value of result
to either "H"
or "T"
.这会将result
的值设置为"H"
或"T"
。
Instead, you should append it.相反,您应该附加它。 You can do this by calling result += "T";
你可以通过调用result += "T";
, or you can use a StringBuilder
and call stringBuilder.append("T");
,或者您可以使用StringBuilder
并调用stringBuilder.append("T");
. .
You have to move random generation into the loop so the chance is recalucalted for each throw.您必须将随机生成移动到循环中,以便为每次投掷重新计算机会。 Something like就像是
public static String flipCoin(int numFlips) {
StringBuilder result = new StringBuilder("");
Random rando = new Random();
for (int i = 0; i < numFlips; i++) {
if (rando.nextInt() % 2 == 0) {
result.append("H");
}
else {
result.append("T");
}
}
return result.toString();
}
That way you won't get 10 of the same.这样你就不会得到10个相同的。
Plus your int chance
argument in加上你的int chance
论点
flipCoin(int chance, int numFlips)
is redudant, beacuse you override it with是多余的,因为你用
chance = rando.nextInt();
later in the code.稍后在代码中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.