我正在努力让这个投掷硬币的程序适用于Java。我还是很新的,我很确定我搞砸了一堆。有人可以看看吗?无法弄清楚如何让我的开关保持循环,直到用户输入0来停止硬币翻转:
主要目标是询问用户有多少翻转和多少翻转头尾翻转。然后询问他们是否要继续翻转并将这些翻转添加到已经完成的翻转中,我必须使用ENUM来完成它。 。 。
import java.util.Random;
import java.util.Scanner;
public class CoinTossing {
private enum Coin { HEADS, TAILS };
private static final Random randomNumbers = new Random();
private static final int HEADS = 1;
private static final int TAILS = 2;
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
int quantity = 0;
int headSide = 0;
int tailsSide = 0;
System.out.println("How many times would you like to flip the coin? Enter 0 to end.");
int flipNumber = input.nextInt();
while (flipNumber != 0)
quantity = quantity + flipNumber;
for(int x=1; x<=quantity; ++x);
switch (Flip(null))
{
case HEADS:
headSide++;
break;
case TAILS:
tailsSide++;
break;
}
if (flipNumber == 0)
System.out.println("Your Number of flips is" + HEADS +TAILS);
}
private static int Flip(Random randomNumber) {
int toss;
toss = 1+ randomNumber.nextInt(2);
return toss;
}
}
答案 0 :(得分:3)
while (flipNumber != 0)
quantity = quantity + flipNumber;
这个循环永远不会破坏。没有大括号,这是一个等同于
的单行循环while (flipNumber != 0)
{
quantity = quantity + flipNumber;
}
显然,如果flipNumber不为0,则此循环将永远运行。
答案 1 :(得分:0)
据我所知,您实际上并没有发送任何类型的随机数生成器,因为您传入的参数是<div ng-repeat="item in items">
{{ item.text }}
</div>
。我建议实例化它,然后尝试传入它。
离开我的头顶,添加这一行:
null
然后将开关更改为
Random random = new Random();
可能会解决您的问题。
答案 2 :(得分:0)
你的while循环没有quantity = quantity + flipNumber;
之外的范围。如果您打算让while
循环包含for
循环,请确保包含大括号。
答案 3 :(得分:0)
public class CoinTossing {
private enum Coin { HEADS, TAILS }
private static final Random random = new Random();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int headSide = 0;
int tailsSide = 0;
System.out.println("How many times would you like to flip the coin? Enter 0 to end.");
int flipNumber;
while ((flipNumber = input.nextInt()) != 0) {
for (int x = 0; x <= flipNumber; x++) {
switch (flip()) {
case HEADS:
headSide++;
break;
case TAILS:
tailsSide++;
break;
}
}
System.out.printf("Heads: %d Tails: %d\n", headSide, tailsSide);
}
System.out.println("Your number of flips is " + (headSide + tailsSide));
}
private static Coin flip() {
if (random.nextBoolean()) {
return Coin.HEADS;
} else {
return Coin.TAILS;
}
}
}