使用do-while在java中重启游戏

时间:2014-06-19 22:49:24

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

请帮助解决游戏开关案例需求

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");

}

}

2 个答案:

答案 0 :(得分: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);
    }
}

... by:

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 等分数)

......或:

忘记该规则仅针对拒绝10,20,30和40,score < 43规则已涵盖

干杯;)


因为我感到无聊,我实际上将自己的建议(以及其他一些建议)应用到您的代码中:

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());
    }
}

答案 1 :(得分:0)

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

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);它的(小)问题是它使读者更难确定循环何时退出。没什么大不了的。

祝你好运。