【问题标题】:How to Loop To Get Input Again - Java如何循环以再次获取输入 - Java
【发布时间】:2017-04-29 00:08:08
【问题描述】:

我正在创建一个 21 的游戏,但我一直在思考如何实现循环。我想做的是介绍游戏(“欢迎来到 21!”),让玩家输入 y 来掷骰子,并给他们掷骰子的值。然后,我想返回并要求他们输入 y 来再次掷骰子。如果他们不输入“y”,我希望出现一条消息,告诉他们必须输入 y 才能玩游戏。基本上,他们会一直被问到是否想玩,直到他们按下 y。

到目前为止,这是我的代码。我遇到的问题是,如果用户按“m”而不是“y”,它会告诉他们“输入 y 玩游戏”,但如果用户在那之后按 y,它会继续告诉他们必须按 y(即使他们已经第二次这样做了)。

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

 public class TwentyOne {

 public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Welcome to 21!");

    System.out.print("Roll the dice, y/n?: ");
    String roll1 = input.nextLine();

        while (true) {
            if(roll1.equals("Y") || roll1.equals("y")) {
                int die1 = (int) (Math.random() * 6) + 1;
                int die2 = (int) (Math.random() * 6) + 1;
                int sum1 = die1 + die2;

        System.out.println("Your dice rolled a sum of: " + sum1);
            break;
         } 
        else {
    System.out.println("Please press 'y' to roll the dice and play. ");
              String rollError = input.nextLine();
        }


} 
}

【问题讨论】:

    标签: java loops


    【解决方案1】:

    您已将第二个输入分配给rollErrorString rollError = input.nextLine();,但您没有使用它来检查新的用户输入if(roll1.equals("Y") || roll1.equals("y"))。将String rollError = input.nextLine(); 更改为roll1 = input.nextLine();

    【讨论】:

      【解决方案2】:

      这里将无限提示用户进行新的滚动(全部通过按“y”触发,也请注意 equalsIgnoreCase()),因为这是您所描述的需求。但是,如果您需要结束游戏,请不要忘记关闭 (input.close()) Scanner 对象以防止泄漏。

          Scanner input = new Scanner(System.in);
          System.out.println("Welcome to 21!");
          boolean isYPressed = false;
          String roll1 = "";
      
          while (true) {
              System.out.print("Roll the dice, y/n?: ");
              roll1 = input.nextLine();
              isYPressed = roll1.equalsIgnoreCase("y");
      
              while (!isYPressed) {
                  System.out.println("Please press the Y key");
                  roll1 = input.nextLine();
                  isYPressed = roll1.equalsIgnoreCase("y");
              }
      
              int die1 = (int) (Math.random() * 6) + 1;
              int die2 = (int) (Math.random() * 6) + 1;
              int sum1 = die1 + die2;
      
              System.out.println("Your dice rolled a sum of: " + sum1);
          }
      

      【讨论】:

        猜你喜欢
        • 2023-02-21
        • 1970-01-01
        • 2021-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-26
        • 2019-03-14
        • 2017-05-03
        相关资源
        最近更新 更多