-1

我正在尝试创建一个 java 程序,它接受用户输入的数字,然后多次翻转硬币,然后显示到目前为止已经翻转了多少正面或反面。当我无法弄清楚如何使程序按照用户所说的次数翻转硬币时,我的问题就来了,有什么帮助吗?

package E1;
import java.util.Scanner;
public class E1 {
    public static void main(String[] args) { 
        int hCount = 0;
        int tCount = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("How many coins should be tossed?");
        input.nextInt();
        if (Math.random() < 0.5) {
            System.out.println("Heads");
            hCount++;
        } else {
            System.out.println("Tails");
            tCount++;
        }
    }
}
4

2 回答 2

0

我建议将包名称设置为小写,因为这是一种广泛且良好的做法。

看看这个,它可能是你想要的:

package e1;

import java.util.Scanner;

public class E1 {
    public static void main(String[] args) {
        int hCount = 0;
        int tCount = 0;
        Scanner input = new Scanner(System.in);
        System.out.print("How many coins should be tossed? ");
        int coinsCount = input.nextInt();
        for (int i=0; i < coinsCount; i++) {
            if (Math.random() < 0.5) {
                System.out.println("Heads");
                hCount++;
            } else {
                System.out.println("Tails");
                tCount++;
            }
        }
        System.out.println("Heads: "+hCount+", Tails: "+tCount);
    }
}
于 2017-11-18T02:05:26.047 回答
0

您可以创建一个对话框窗口,用户指示次数,然后您可以解决这个问题,看:

    package E1;
    import java.util.Scanner;
    import javax.swing.*; // shows the dialogs windows

        public class E1 {
        public static void main(String[] args){

        // This Dialog Window will ask the User how many times the coin will be tossed
                int n_of_flips = JOptionPane.showInputDialog(null, 
                    "Please indicate how many times you wish to flip the coin",
                    "Coin Flip",
                    JOptionPane.QUESTION_MESSAGE);


           // the while loop
           int x = 0;
           while(x<= n_of_flips){
            // your code here:
            if (Math.random() < 0.5)
                {
                System.out.println("Heads");
                        x++;
            }else{
                System.out.println("Tails");
                            x++;
            } // END while loop

       } // END public static void

    } // END of E1

有关更多信息 google “JOptionPane Java”,您还可以在对话窗口中显示您的结果。玩得开心 :

于 2017-11-18T00:22:09.397 回答