Как создать непрерывный цикл для игры с подбрасыванием монет на Java?

#java

#java

Вопрос:

У меня возникают проблемы при попытке выполнить обратный цикл моего кода и выполнить программу заново, пока пользователь не попросит их остановиться, введя ноль. Я попробовал оператор while, но я не уверен, правильно ли я его реализовал, поскольку все, что я получил, было ошибками. Я ценю любую помощь, которую можно оказать. Я включил свой код ниже.

 public class CoinTossing {

    public static void main(String[] args) {

//Scanner method
        Scanner input = new Scanner(System.in);
        int choice;

        System.out.println("Welcome to the Coin Toss Program.");

//Variables for the count of heads and tails.
        int headCount = 0;
        int tailCount = 0;

        System.out.println("How many coin flips do you want to do?");
        int number = input.nextInt();
        for (int i = 1; i <= number; i  ) {
            Random rand = new Random();

            // Simulate the coin tosses.
            for (int count = 0; count < number; count  ) {

                if (rand.nextInt(2) == 0) {
                    tailCount  ;
                } else {
                    headCount  ;
                }
            }
            System.out.println("Times head was flipped:"   headCount);
            System.out.println("Times tail was flipped:"   tailCount);
            return;
        }
    }

}
  

Комментарии:

1. «Я попробовал оператор while, но я не уверен, правильно ли я его реализовал, поскольку все, что я получил обратно, было ошибками». — Показанный код не содержит использования while цикла, и в описании не указаны какие-либо ошибки. Можете ли вы обновить вопрос, включив в него код, который демонстрирует проблему, а также информацию о проблеме, которую вы наблюдали?

Ответ №1:

Ваш основной метод может выглядеть примерно так:

 public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Welcome to the Coin Toss Program.");

        //Variables for the count of heads and tails.
        
        while (true) {
            int headCount = 0;
            int tailCount = 0;

            System.out.println("How many coin flips do you want to do?");
            int number = input.nextInt();

            if (number == 0) { break; }

            Random rand = new Random();
            // Simulate the coin tosses.
            for (int i = 0; i < number; i  ) {
                if (rand.nextInt(2) == 0) {
                    tailCount  ;
                } else {
                    headCount  ;
                }
            }
            
            System.out.println("Times head was flipped:"   headCount);
            System.out.println("Times tail was flipped:"   tailCount);
        }
    }
  

Здесь цикл while вводится после приветственного сообщения и завершает симуляцию только тогда, когда пользователь вводит 0.

После того, как пользовательский ввод будет восстановлен, он проверит, был ли пользовательский ввод 0. Если пользователь вводит 0, это будет break цикл while, прежде чем программа имитирует подбрасывание монеты:

 if (number == 0) { break; }
  

Ответ №2:

Поместите свой код в цикл while, за исключением этих двух строк:

 Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Coin Toss Program.");
  

В конце игры с подбрасыванием монет естественным порядком вещей было бы спросить пользователя, хочет ли он / она играть снова. Это позволяет пользователю выйти из приложения, а не застрять в непрерывном цикле:

 String yn = "y";
while (yn.equalsIgnoreCase("y")) {
    int headCount = 0;
    int tailCount = 0;
    int number = 0;
    String num = null;
    while (num == null) {
        System.out.print("How many coin flips do you want to do? --> ");
        num = input.nextLine();
        if (!num.matches("\d ")) {
            System.err.println("Invalid Integer Number Supplied (" 
                               num   ")! Try Again...");
            System.out.println();
            num = null;
        }
    }
    number = Integer.valueOf(num);
    // Simulate the coin tosses.
    for (int i = 1; i <= number; i  ) {
        if (rand.nextInt(2) == 0) {
            tailCount  ;
        }
        else {
            headCount  ;
        }
    }
    System.out.println("Times head was flipped:"   headCount);
    System.out.println("Times tail was flipped:"   tailCount);

    System.out.println();
    while (yn.equalsIgnoreCase("y")) {
        System.out.print("Do you want to play again? (y/n) --> ");
        yn = input.nextLine();
        if (yn.matches("[yYnN]")) {
            System.out.println();
            break;
        }
        else {
            System.err.println("Invalid response ("   yn   ")! 'y' or 'n' only!");
            System.out.println();
            yn = "y";
        }
    }
}
  

Все приложение может выглядеть примерно так:

 public class CoinTossing {

    public static void main(String[] args) {
        java.util.Scanner input = new java.util.Scanner(System.in);
        java.util.Random rand = new java.util.Random();
        System.out.println("Welcome to the Coin Toss Program");
        System.out.println("================================");
        System.out.println();

        String yn = "y";
        while (yn.equalsIgnoreCase("y")) {
            int headCount = 0;
            int tailCount = 0;
            int number = 0;
            String num = null;
            while (num == null) {
                System.out.print("How many coin flips do you want to do? --> ");
                num = input.nextLine();
                if (!num.matches("\d ")) {
                    System.err.println("Invalid Integer Number Supplied (" 
                                       num   ")! Try Again...");
                    System.out.println();
                    num = null;
                }
            }
            number = Integer.valueOf(num);
            // Simulate the coin tosses.
            for (int i = 1; i <= number; i  ) {
                if (rand.nextInt(2) == 0) {
                    tailCount  ;
                }
                else {
                    headCount  ;
                }
            }
            System.out.println("Times head was flipped:"   headCount);
            System.out.println("Times tail was flipped:"   tailCount);

            System.out.println();
            while (yn.equalsIgnoreCase("y")) {
                System.out.print("Do you want to play again? (y/n) --> ");
                yn = input.nextLine();
                if (yn.matches("[yYnN]")) {
                    System.out.println();
                    break;
                }
                else {
                    System.err.println("Invalid response ("   yn   ")! 'y' or 'n' only!");
                    System.out.println();
                    yn = "y";
                }
            }
        }
    }
}