我正在尝试编写一个脚本,它会给我10个抛硬币的摘要。我被困在如何阅读结果和输出这样的摘要:
C:\用户\ javauser \桌面和GT; java CoinToss
负责人:3
尾巴:7
这是我的代码:
import java.util.Random;
public class CoinToss{
public static void main(String[] args)
{
Random rand = new Random();
for (int i = 0; i < 10; i++)
{
if (rand.nextInt(2) == 0)
System.out.println("Tails");
else
System.out.println("Heads");
}
}
}
答案 0 :(得分:3)
跟踪结果而不是立即打印,然后打印出最终结果。我在这里使用了String格式来保持String的连接不被连接。
import java.util.Random;
public class CoinToss{
public static void main(String[] args)
{
Random rand = new Random();
int heads = 0;
int tails = 0;
for (int i = 0; i < 10; i++)
{
if (rand.nextInt(2) == 0)
tails++;
else
heads++;
}
String results = String.format("CoinToss Heads: %d Tails: %d", heads, tails);
System.out.printLn(results);
}
}
答案 1 :(得分:1)
您需要跟踪模拟结果。
import java.util.Random;
public class CoinToss{
public static void main(String[] args)
{
Random rand = new Random();
int numHeads = 0;
int numTails = 0;
for (int i = 0; i < 10; i++)
{
if (rand.nextInt(2) == 0)
numTails++;
else
numHeads++;
}
System.out.println("Heads: " + numHeads);
System.out.println("Tails: " + numTails);
}