【问题标题】:Using a do-while to restart a game in java在java中使用do-while重新启动游戏
【发布时间】:2014-08-10 15:09:48
【问题描述】:

请帮忙解决游戏的开关盒需求

public static void main(String[] args) {

Scanner input = new Scanner(System.in);
System.out.print("Please Enter a number");
int day = input.nextInt();

switch(day)
{
case 1: System.out.println("1 Microphone");
break;
case 2: System.out.println("2 Loud Speakers 1 Microphone ");
break;
case 3: System.out.println("3 Keyboards  2 Loudspeakers 1 Microphone ");
break;
case 4: System.out.println("4 Java Books 3 Keyboards  2 Loudspeakers 1 Microphone");
break;
case 5: System.out.println("5 Iphones 4 Java Books 3 Keyboards  2 Loudspeakers 1 Microphone");
break;

default: System.out.println("Enter A Valid Prize Day");

}

}

【问题讨论】:

  • 你应该设置变量 maxRolls = 7 和 sum = 0;
  • 我只是看了一眼代码。把你的代码放在一个 while(true) 循环中,然后用一个 break 指令离开 do while 循环怎么样?您将在 mail 方法之后再次开始,变量将被重新初始化。
  • 我将如何做一个真正的循环?

标签: java for-loop restart do-while dice


【解决方案1】:

正如@AlexandreSantos 指出的,每次重启游戏时都需要重新初始化maxRollssum 的值。也就是说,这些初始化应该是在您的 do {} while () 循环中执行的第一件事。

do {
    int maxRolls = 7;
    int sum = 0;

    // ... 

} while (option);

我还会给你其他建议:

  • Java 中,按照惯例,类名以大写字母开头。因此,我会将您的班级命名为 Game 而不是 game

以下代码(以及与"no" 等效的代码):

(userInputTwo.equals("Yes") || userInputTwo.equals("yes") || userInputTwo.equals("YES"))

... 可以替换为:

userInputTwo.equalsIgnoreCase("yes")

...因为,正如您在问题中提到的那样,您实际上只是试图忽略这种情况;)

  • 您正在在两个地方询问用户是否要重新启动。在打印 "You won""You lost" 之后,您实际上可以(应该)简单地执行一次。

我建议更换:

if (sum >= 43) {
    System.out.println("You Win");
    System.out.print("Would You Like To Play Again . Yes or No?");
    final String userInput = input.nextLine();
    if (userInput.equals("Yes") || userInput.equals("yes") || userInput.equals("YES")) {
        // MISSING CODE TO RESTART THE PROGRAM
        option = true;
    } else if (userInput.equals("No") || userInput.equals("no") || userInput.equals("NO")) {
        System.exit(0);
    }
}
if (sum < 43 || sum % 10 == 0) {
    System.out.println("You Lose");
    System.out.print("Would You Like To Play Again . Yes or No?");
    final String userInputTwo = input.nextLine();
    if (userInputTwo.equals("Yes") || userInputTwo.equals("yes") || userInputTwo.equals("YES")) {
        option = true;
        // MISSING CODE TO RESTART THE PROGRAM
    } else if (userInputTwo.equals("No") || userInputTwo.equals("no") || userInputTwo.equals("NO")) {
        System.exit(0);
    }
}

...作者:

if (sum >= 43) {
    System.out.println("You Win");
}

if (sum < 43 || sum % 10 == 0) {
    System.out.println("You Lose");
}

System.out.print("Would You Like To Play Again . Yes or No?");
final String userInput = input.nextLine();
if ("yes".equalsIgnoreCase(userInput) {
    // MISSING CODE TO RESTART THE PROGRAM
    option = true;
} else if ("no".equalsIgnoreCase(userInput)) {
    System.exit(0);
}

...或者,更好的是,将其提取到其他方法中。

或者,甚至更好,甚至不检查其中一种可能性并将其设为默认值,以防用户输入既不是"yes" 也不是"no" 的内容:

private static boolean restart(final Scanner input) {
    // I choose to interpret any input that's different from "yes" as a "no".
    System.out.print("Would You Like To Play Again. Yes or No? (default: No)");
    final String userInput = input.nextLine();
    if ("yes".equalsIgnoreCase(userInput)) {
        return true;
    }

    return false;
}

... 这显然可以变成:

private static boolean restart(final Scanner input) {
    // I choose to interpret any input that's different from "yes" as a "no".
    System.out.print("Would you like to play again? [Yes/No] (default: No)");
    return "yes".equalsIgnoreCase(input.nextLine());
}

...option 变量可能会消失:

do {
   ...
} while (Game.restart(input));
  • 您可以(应该)使用Random 而不是Math.random(),这样更方便。

例如:

final int dieOne = (int) (Math.random() * faces) + 1;
final int dieTwo = (int) (Math.random() * faces) + 1;
final int totalRollForRound = dieOne + dieTwo;

...可能变成:

// Outside of the do {} while ():
final Random r = new Random();

// Inside the do {} while ():
final int totalRollForRound = r.nextInt(faces) + r.nextInt(faces) + 2;
  • 应始终在退出程序之前关闭Scanner

使用try-with-resources 语法:

private static boolean restart() {
    try (final Scanner input = new Scanner(System.in) {
        // I choose to interpret any input that's different from "yes" as a "no".
        System.out.print("Would you like to play again? [Yes/No] (default: No)");
        return "yes".equalsIgnoreCase(input.nextLine());
    }
}
  • 最后一件事:你的sum % 10 == 0 很奇怪:你已经告诉用户,如果他得分至少为 43,他就赢了,如果他得分低于 43,他就会输……你应该:李>

在检查用户得分是否超过 43 之前测试该条件(因此也会拒绝 50、60、70、80 等分数...)

... 或:

忘记这条规则,它只旨在拒绝 score &lt; 43 规则已经涵盖的 10、20、30 和 40。

干杯 ;)


只是因为我觉得无聊,我实际上将我自己的建议(以及其他一些建议)应用于您的代码:

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

public class Game {

    private static final int FACES = 6;
    private static final int MAX_ROLLS = 7;
    private static final Random R = new Random();

    public static void main(final String[] args) {
        try (final Scanner input = new Scanner(System.in)) {
            do {
                if (Game.roll() >= 43) {
                    System.out.println("You won!");
                } else {
                    System.out.println("You lost.");
                }
            } while (Game.restart(input));
        }
    }

    private static int roll() {
        int maxRolls = MAX_ROLLS;
        int sum = 0;

        for (int i = 1; i < maxRolls; i++) {
            final int dieOne = R.nextInt(FACES) + 1;
            final int dieTwo = R.nextInt(FACES) + 1;
            sum += dieOne + dieTwo;
            System.out.println("Roll #" + i + ": You rolled " + dieOne + " and " + dieTwo + ".\tYour new total is: " + sum);

            if (dieOne == dieTwo) {
                System.out.println("DOUBLES! You get an extra roll.");
                maxRolls++;
            }
        }

        return sum;
    }

    private static boolean restart(final Scanner input) {
        System.out.print("Play again? [Yes/No] (default: No): ");
        return "yes".equalsIgnoreCase(input.nextLine());
    }
}

【讨论】:

    【解决方案2】:

    听起来你想要一个外循环;每次通过循环用户玩一个游戏。在该循环的顶部,您初始化玩一场游戏所需的值:

    boolean playingMoreGames = false;
    do
    {
      int sum = 0;
      int maxRolls = 6;
      int rollsMade = 0;
      boolean gameOver = false;
      do
      { 
        // roll dice
        // determine win or loss
        // and determine whether game is over
        // include testing rollsMade against maxRolls
      }
      while (!gameOver)
      // ask user whether he wants to play again and set playingMoreGames accordingly
    }
    while (playingMoreGames);
    

    我建议更改 while 循环,只要未达到 maxRolls 就会执行。在循环内修改 for 循环的目标不是一个好主意;至少在某些语言中,行为是未定义的,它使读者感到困惑。由于maxRolls 可以更改,因此您需要一个不同的循环形式。

    而且你真的不需要打电话给System.exit();如果你“掉出”主程序的底部,你的程序将退出,因为它没有更多的指令可以执行。

    在这种情况下我不推荐do while(true);它的(小)问题是它使读者更难确定循环何时退出。没什么大不了的。

    祝你好运。

    【讨论】:

      猜你喜欢
      • 2015-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-22
      • 2021-08-30
      • 1970-01-01
      相关资源
      最近更新 更多