-3

好的,我是 java 的初学者,在柜台上苦苦挣扎。我正在尝试查找计数并打印翻转硬币正面和反面的出现次数。当我运行我的代码时,它会在每一行打印每个事件的发生情况。我希望它是一个累积计数并在最后打印。如果能帮忙谢谢!Ps:我还没有实现tailCounter,因为我想先弄清楚正面。

import java.util.Random;
import java.util.Scanner;

public class InClass7_1
{

    public static void main(String[] args)
    {
        int flipcount;
        Scanner scannerObject = new Scanner(System.in);
        System.out.println ("Enter a number of times to flip the coin");
        flipcount = scannerObject.nextInt();

        Random randomGenerator = new Random();
        int counter = 1;
        while (counter <= flipcount)
        {
            System.out.print("Flip number " + counter + ": ");
            int coinFlip = randomGenerator.nextInt(2);
            int headCounter = 0;
            int tailCounter = 0;

            if (coinFlip == 1)
            {
                System.out.println("Heads");
            }
            else
            {
                System.out.println("Tails");
            }
            counter++;

            if (coinFlip == 1)
                headCounter++;

            System.out.println("Times head was flipped: " + headCounter);
        }   
    }
}
4

1 回答 1

0

headCounterandtailCounter变量移到 while 循环上方,并根据它们在 if-else 构造中的外观递增。将 print 语句移到 while 循环下方。

public static void main(String[] args) {
    int flipcount;
    Scanner scannerObject = new Scanner(System.in);
    System.out.println("Enter a number of times to flip the coin");
    flipcount = scannerObject.nextInt();
    Random randomGenerator = new Random();
    int counter = 1;
    int headCounter = 0;
    int tailCounter = 0;
    while (counter <= flipcount) {
        System.out.print("Flip number " + counter + ": ");
        int coinFlip = randomGenerator.nextInt(2);
        if (coinFlip == 1) {
            System.out.println("Heads");
            headCounter++;
        } else {
            System.out.println("Tails");
            tailCounter++;
        }
        counter++;            
    }
    System.out.println("Times head was flipped: " + headCounter);
    System.out.println("Times tails was flipped: " + tailCounter);
}
于 2019-11-16T19:44:02.313 回答