繁体   English   中英

计算出现次数。 (初学者)

[英]Counting the number of occurrences. (beginner)

好的,我是 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);
        }   
    }
}

headCountertailCounter变量移到 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM