使用一个do-while在java中重新开始一个游戏 [英] Using a do-while to restart a game in java

查看:219
本文介绍了使用一个do-while在java中重新开始一个游戏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



public static void main(String [] args){

 扫描仪输入=新扫描仪(System.in); 
System.out.print(请输入一个数字);
int day = input.nextInt();

switch(day)
{
case 1:System.out.println(1 Microphone);
break;
情况2:System.out.println(2 Loud Speakers 1 Microphone);
break;
情况3:System.out.println(3键盘2扬声器1麦克风);
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;

默认:System.out.println(输入有效的奖金日);

$ b

}

解决方案 @AlexandreSantos指出,你需要重新初始化 maxRolls sum 每次重新启动游戏。也就是说,这些初始化应该是您的 while()循环中执行的第一件事情。

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

// ...

} while(option);

我还会给你其他的建议:

Java


  • ,按照惯例,类名称以大写字母开头。因此,我会命名您的课程游戏而不是游戏



以下代码(及其与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(你愿意再玩吗?是或否?);
final String userInput = input.nextLine();
if(userInput.equals(Yes)|| userInput.equals(yes)|| userInput.equals(YES)){
//缺少重新启动程序的代码
option = true;
} else if(userInput.equals(No)|| userInput.equals(no)|| userInput.equals(NO)){
System.exit(0);

$ b if(sum< 43 || sum%10 == 0){
System.out.println(You Lose);
System.out.print(你愿意再玩吗?是或否?);
final String userInputTwo = input.nextLine();
if(userInputTwo.equals(Yes)|| userInputTwo.equals(yes)|| userInputTwo.equals(YES)){
option = true;
// MISSING代码重启程序
} else if(userInputTwo.equals(No)|| userInputTwo.equals(no)|| userInputTwo.equals(NO)){
System.exit(0);





y $ <$ p

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


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


System.out.print(你愿意再玩吗?是或否?
final String userInput = input.nextLine();
if(yes.equalsIgnoreCase(userInput){
// MISSING CODE重新启动程序
option = true;
} else if(no.equalsIgnoreCase(userInput )){
System.exit(0);
}

或者甚至更好地将其提取到另一个方法中。

或者甚至更好,甚至不检查其中一个可能性并使其成为默认值,以防万一用户输入的内容不是yes也不是no

  private static boolean restart(final Scanner input){
//我选择将任何与yes不同的输入解释为no。 $ b System.out.print(你想再次玩吗?是或否?(默认值:否));
final String userInput = input.nextLine();
if(yes .equalsIgnoreCase(userInput)){
return true;
}

return false;
}

...这显然可以变成:

  private static boolean restart(final Scanner input){
//我选择将任何不同于yes的输入解释为没有。
System.out.print(你想再玩吗?[Yes / No](默认:No));
返回yes.equalsIgnoreCase(input.nextLine());

$ / code>

...和选项


while(Game.restart (输入));你可以(应该)使用随机



$ b $ / code>而不是 Math.random(),它只是方便一些。


例如:

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

...可能会变成:

<$ p ():
最终的随机数r = new Random();
$ b $ // //在do {} while()中:
final int totalRollForRound = r.nextInt(faces)+ r.nextInt(faces)+ 2;




  • 应始终 / strong>在离开程序之前关闭 Scanner


    使用< $ b $ href =http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html =nofollow>试用资源语法:

      private static boolean restart(){
    try(final Scanner input = new Scanner(System.in){
    // I choose (你愿意再玩一次吗?[Yes / No](默认值:No)); $ b $可以将任何不同于yes的输入解释为no
    System.out.print b返回yes.equalsIgnoreCase(input.nextLine());
    }
    }




    • 最后一件事是:你的总和%10 == 0 很奇怪:你已经告诉用户他赢了,如果他得分至少为43分,如果他得分低于43分,他将会输球。你应该:


    测试这个条件,然后检查用户是否得分超过43 (因此也拒绝50,60,70,80等分数)。



    ...或者:

    忘记那个仅仅拒绝10,20,30和40的规则 得分已经 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();
    $ b $ 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; (int i = 1; i final int dieOne = R.nextInt(FACES)+ 1;

    ;
    final int dieTwo = R.nextInt(FACES)+ 1;
    sum + = dieOne + dieTwo;
    System.out.println(Roll#+ i +:你滚动了+ dieOne +和+ dieTwo +,你的新总数是:+ sum);

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

    归还金额;

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


    Please help with the swtich case need for a game

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

    }

    解决方案

    As @AlexandreSantos pointed out, you need to reinitialise the values of maxRolls and sum every time you restart the game. That is, these initialisations should be the first things executed in your do {} while () loop.

    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. Thus, I'd name your class Game instead of game.

    The following code (and its equivalent with "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".

    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":

    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:

    do {
       ...
    } while (Game.restart(input));
    

    • You could (should) use Random instead of Math.random(), it's just way more convenient.

    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.

    Use the try-with-resources syntax:

    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:

    Test that condition before checking whether the user has scored more than 43 (and therefore also rejecting scores like 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.

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

    这篇关于使用一个do-while在java中重新开始一个游戏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆