简体   繁体   English

使用do-while重新启动Java游戏

[英]Using a do-while to restart a game in java

Please help with the swtich case need for a game 请帮助游戏的案件

public static void main(String[] args) { 公共静态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");

}

} }

As @AlexandreSantos pointed out, you need to reinitialise the values of maxRolls and sum every time you restart the game. 正如@AlexandreSantos指出的那样,您需要重新初始化maxRolls的值,并在每次重新启动游戏时进行sum That is, these initialisations should be the first things executed in your do {} while () loop. 也就是说,这些初始化应该是您在do {} while ()循环中执行的第一件事。

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

    // ... 

} while (option);

I'd also give you other recommendations: 我还会给您其他建议:

  • in Java , the class names, by convention, start with an upper-case letter. Java中 ,按照惯例,类名以大写字母开头。 Thus, I'd name your class Game instead of game . 因此,我将您的班级命名为Game而不是game

The following code (and its equivalent with "no" ): 以下代码(及其等效于"no" ):

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

... can be replaced by: ...可以替换为:

userInputTwo.equalsIgnoreCase("yes")

... since, as you mentioned in your question, you're actually simply trying to ignore the case ;) ...因为正如您在问题中提到的那样,您实际上只是在试图忽略这种情况;)

  • You're doing all that asking the user whether is wants to restart or not in two places . 您要做的就是在两个地方询问用户是否要重新启动。 You could (should) actually simply do it once, after having printed either "You won" or "You lost" . 在打印"You won""You lost"之后, "You won"实际上可以(应该)只做一次。

I'd suggest to replace: 我建议更换:

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

... or, even better, extracting this into an other method. ...或者甚至更好地将其提取到其他方法中。

Or, even better, not even checking for one of the possibilities and make it the default one, in case the user enters something that's neither "yes" nor "no" : 或者,甚至更好,甚至没有检查的可能性之一,并使其成为默认的,万一用户输入的东西,既不"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;
}

... which can obviously then become: ...显然可以变成:

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

... and the option variable could disappear: ...,而option变量可能会消失:

do {
   ...
} while (Game.restart(input));
  • You could (should) use Random instead of Math.random() , it's just way more convenient. 您可以(应该)使用Random代替Math.random() ,这只是更方便。

For example: 例如:

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

... could become: ...可能会变成:

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

// Inside the do {} while ():
final int totalRollForRound = r.nextInt(faces) + r.nextInt(faces) + 2;
  • You should always close the Scanner before leaving the program. 退出程序之前, 应始终关闭Scanner

Use the try-with-resources syntax: 使用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());
    }
}
  • One last thing: your sum % 10 == 0 is weird: you've already told the user that he won if he scored at least 43, and he's gonna lose if he scored less than 43... You should either: 最后一件事:您的sum % 10 == 0很奇怪:您已经告诉用户,如果他的得分至少为43,他就赢了;如果他的得分小于43,他将会输。。。

Test that condition before checking whether the user has scored more than 43 (and therefore also rejecting scores like 50, 60, 70, 80 ...) 在检查用户得分是否超过43之前测试该条件(并因此拒绝得分50、60、70、80 ...)

... or: ... 要么:

Forget about that rule that only aims to reject 10, 20, 30 and 40, which are already covered by the score < 43 rule. 忘记只拒绝拒绝score < 43规则已涵盖的10、20、30和40的规则。

Cheers ;) 干杯;)


Just 'cause I felt bored, I actually applied my own advices (and a few more) to your code: 只是因为我感到无聊,所以我实际上将自己的建议(以及更多建议)应用于了您的代码:

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

Sounds like you want an outer loop; 听起来好像您想要一个外部循环; each time through the loop the user plays one game. 每次用户循环玩一次游戏。 At the top of that loop, you initialize the values that you need to play one game: 在该循环的顶部,您初始化玩一个游戏所需的值:

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

I have suggested a change to a while loop that executes as long as the maxRolls has not been reached. 我建议更改为while循环,只要未达到maxRolls执行。 It is not a good idea to modify the target of a for loop within the loop; 在循环内修改for循环的目标不是一个好主意。 in some languages, at least, the behavior is undefined, and it confuses the reader. 至少在某些语言中,行为是不确定的,这会使读者感到困惑。 Since maxRolls can change, you need a different looping form there. 由于maxRolls可以更改,因此您需要在那里使用其他循环形式。

And you don't really need to call System.exit() ; 而且您实际上不需要调用System.exit() if you "fall out of" the bottom of your main routine, your program will just exit since it has no more instructions to execute. 如果您“脱离”主程序的底部,则程序将退出,因为它没有更多要执行的指令。

I don't recommend do while(true) in this case; 我不建议在这种情况下do while(true) the (small) problem with it is that it makes it harder for the reader to determine when the loop exits. 它的(小)问题在于,它使读者更难确定何时退出循环。 Not a big deal. 没有大碍。

Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM