我可以阻止用户在循环中选择相同的 switch case 两次吗?

发布于 2025-01-12 19:21:58 字数 1265 浏览 1 评论 0原文

我必须使用扫描仪制作骰子游戏。 我将有 3 个骰子,用户将被要求选择扔哪一个。 用户不能一次扔掉所有的东西——只能一个接一个地挑选。 在一轮 3 次投掷中不允许使用同一个骰子两次,但用户可以按照自己想要的顺序拿走骰子。 比赛的总比分即将达到12分。 我尝试过使用 if 语句和 switch - 但我还没有找到解决方案,让用户不能两次接受相同的模具。 我删除了一些代码,但我用 switch 再次尝试。

我的代码是:

// 声明变量

int diceOne = 0;
int diceTwo = 0;
int diceThree = 0;
int rolls;
int rollOne;
int rollTwo;
int rollThree;
int rounds=1;
int sumOfDice =0;


String welcome = "[ Welcome to the game 12! Try to get the total sum of 12 by rolling 1-3 dices ]";
String userInfo = "Enter which dice you want to roll [1,2,3] (Exit game with q): ";


// Create Scanner to obtain data input from user.

Scanner twelf = new Scanner(System.in);

// Welcome message

System.out.print("\n" + welcome + "\n");

// while loop

while(rounds<=3){
System.out.print("\n"+userInfo + " ");
rolls = twelf.nextInt(); 
rounds= rounds + 1; 
rolls =+ rolls;
  

  
switch(rolls){

  case 1:

  diceOne = (int)(Math.random()*6)+1;
  System.out.print("Dice 1 hits " + diceOne); 

  
  break;


  case 2:
   
    diceTwo = (int)(Math.random()*6)+1;  
    System.out.print("Dice 2 hits " + diceTwo);
   break; 

  case 3:
  diceThree = (int)(Math.random()*6)+1;
    System.out.print("Dice 3 hits " + diceThree);
  break;
  default:  
    
    
} 

I have to make a dice game using Scanner.
I will have 3 dice and the user will be asked to choose which one to throw.
The user can't throw all at once - just pick one after another.
It's not allowed to use the same die twice in one round of 3 throws, but user can take the dices in the order user wants.
The game is about to hit a sum of 12.
I have tried to use if statements and switch - but I haven't found a solution for that user can't take same die twice.
I erased some code, but I tried again with switch.

My code is:

// Declaring variables

int diceOne = 0;
int diceTwo = 0;
int diceThree = 0;
int rolls;
int rollOne;
int rollTwo;
int rollThree;
int rounds=1;
int sumOfDice =0;


String welcome = "[ Welcome to the game 12! Try to get the total sum of 12 by rolling 1-3 dices ]";
String userInfo = "Enter which dice you want to roll [1,2,3] (Exit game with q): ";


// Create Scanner to obtain data input from user.

Scanner twelf = new Scanner(System.in);

// Welcome message

System.out.print("\n" + welcome + "\n");

// while loop

while(rounds<=3){
System.out.print("\n"+userInfo + " ");
rolls = twelf.nextInt(); 
rounds= rounds + 1; 
rolls =+ rolls;
  

  
switch(rolls){

  case 1:

  diceOne = (int)(Math.random()*6)+1;
  System.out.print("Dice 1 hits " + diceOne); 

  
  break;


  case 2:
   
    diceTwo = (int)(Math.random()*6)+1;  
    System.out.print("Dice 2 hits " + diceTwo);
   break; 

  case 3:
  diceThree = (int)(Math.random()*6)+1;
    System.out.print("Dice 3 hits " + diceThree);
  break;
  default:  
    
    
} 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猫弦 2025-01-19 19:21:58

程序到底要求什么以及输出应该是什么仍然有点模糊。但似乎您可能需要一个条件语句来检查某些骰子是否已经掷出。

int diceOne = 0;
        int diceTwo = 0;
        int diceThree = 0;
        int rolls;
        int rollOne;
        int rollTwo;
        int rollThree;
        int rounds = 1;
        int sumOfDice = 0;


        String welcome = "[ Welcome to the game 12! Try to get the total sum of 12 by rolling 1-3 dices ]";
        String userInfo = "Enter which dice you want to roll [1,2,3] (Exit game with q): ";


// Create Scanner to obtain data input from user.

        Scanner twelf = new Scanner(System.in);

// Welcome message

        System.out.println("\n"+welcome +"\n");

// while loop

        while(rounds<=3)

        {
            System.out.print("\n" + userInfo + " ");
            rolls = twelf.nextInt();
            rounds = rounds + 1;
            rolls = +rolls;


            switch (rolls) {

                case 1:
                    if(diceOne > 0) {
                        System.out.println("Cannot roll same dice more than once"); // add a condition that meets your needs to check before rolling the die. //
                    } else {
                        diceOne = (int) (Math.random() * 6) + 1;
                        System.out.print("Dice 1 hits " + diceOne);


                        break;
                    }


                case 2:
                    if(diceTwo > 0) {
                        System.out.println("Cannot roll same dice more than once"); // add a condition that meets your needs to check before rolling the die. //
                    } else {
                        diceTwo = (int) (Math.random() * 6) + 1;
                        System.out.print("Dice 2 hits " + diceTwo);
                        break;
                    }

                case 3:
                    if(diceThree > 0) {
                        System.out.println("Cannot roll same dice more than once"); // add a condition that meets your needs to check before rolling the die. //
                    } else {
                        diceThree = (int) (Math.random() * 6) + 1;
                        System.out.print("Dice 3 hits " + diceThree);
                        break;
                    }
                default:


            }
        }
    }
}

It's still a little vague what exactly the program is asking and what the output should be. But it seems that you might need a conditional statement that checks if that certain dice had been rolled already.

int diceOne = 0;
        int diceTwo = 0;
        int diceThree = 0;
        int rolls;
        int rollOne;
        int rollTwo;
        int rollThree;
        int rounds = 1;
        int sumOfDice = 0;


        String welcome = "[ Welcome to the game 12! Try to get the total sum of 12 by rolling 1-3 dices ]";
        String userInfo = "Enter which dice you want to roll [1,2,3] (Exit game with q): ";


// Create Scanner to obtain data input from user.

        Scanner twelf = new Scanner(System.in);

// Welcome message

        System.out.println("\n"+welcome +"\n");

// while loop

        while(rounds<=3)

        {
            System.out.print("\n" + userInfo + " ");
            rolls = twelf.nextInt();
            rounds = rounds + 1;
            rolls = +rolls;


            switch (rolls) {

                case 1:
                    if(diceOne > 0) {
                        System.out.println("Cannot roll same dice more than once"); // add a condition that meets your needs to check before rolling the die. //
                    } else {
                        diceOne = (int) (Math.random() * 6) + 1;
                        System.out.print("Dice 1 hits " + diceOne);


                        break;
                    }


                case 2:
                    if(diceTwo > 0) {
                        System.out.println("Cannot roll same dice more than once"); // add a condition that meets your needs to check before rolling the die. //
                    } else {
                        diceTwo = (int) (Math.random() * 6) + 1;
                        System.out.print("Dice 2 hits " + diceTwo);
                        break;
                    }

                case 3:
                    if(diceThree > 0) {
                        System.out.println("Cannot roll same dice more than once"); // add a condition that meets your needs to check before rolling the die. //
                    } else {
                        diceThree = (int) (Math.random() * 6) + 1;
                        System.out.print("Dice 3 hits " + diceThree);
                        break;
                    }
                default:


            }
        }
    }
}
白云不回头 2025-01-19 19:21:58

您可能希望使用映射来跟踪骰子是否掷出,而不是使用 switch 语句。 rolledDiceMap 将存储您的三个骰子,它有一个 Integer 键和一个 Dice 值。

为此,我创建了一个 Dice 类,它有两个字段:

  • value:滚动的随机值;
  • rolled:布尔标志,如果为 true,则重复 while 循环,直到用户输入合适的值并进入下一轮。

我尝试在下面的代码中添加一些希望有用的注释:

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class RollDice {
    public static final String WELCOME = "[ Welcome to the game 12! Try to get the total sum of 12 by rolling 1-3 dices ] ";
    public static final String USER_INFO = "Enter which dice you want to roll [1,2,3] (Exit game with q): ";
    public static final String WRONG_DIE_VALUE = "Please enter a good die value";
    public static final String DIE_ROLLED = "Die already rolled, please roll a new die";
    public static final String CONGRATULATIONS = "You rolled 12, congratulations !";
    public static final String GOOD_LUCK = "Good luck next time, your dice rolled: ";

    public static void main(String[] args) {
        int rounds = 1;
        int sum = 0;

        // Create Scanner to obtain data input from user.
        Scanner twelf = new Scanner(System.in);

        System.out.println(WELCOME);

        Map<Integer, Dice> rolledDiceMap = new HashMap();

        // Generate a key value pair for three dice e.g.: (1, Dice); (2, Dice); (3, Dice)
        for (int i = 1; i <= 3; i++) {
            rolledDiceMap.put(i, new Dice());
        }

        while (rounds <= 3) {
            System.out.print(USER_INFO);
            int rolledValue = twelf.nextInt();

            // check if user input is valid (user entered 1,2 or 3)
            if (rolledDiceMap.containsKey(rolledValue)) {
                Dice rolledDie = rolledDiceMap.get(rolledValue);

                // check if die was rolled, if yes, repeat round
                if(rolledDie.wasRolled()){
                    System.out.println(DIE_ROLLED);
                    // repeat round
                    continue;
                }

                // set rolled to true and assign a random value
                rolledDie.setRolled(true);
                int value = (int) (Math.random() * 6) + 1;
                rolledDie.setValue((int) (Math.random() * 6) + 1);

                sum += value;

                System.out.println("You rolled: " + value);
            } else {
                System.out.println(WRONG_DIE_VALUE);
                // repeat round
                continue;
            }

            // move to next round
            rounds++;
        }

        // print result
        if(sum == 12){
            System.out.println(CONGRATULATIONS);
        } else{
            System.out.println(GOOD_LUCK + sum);
        }
    }

    static class Dice {
        private Integer value;
        private boolean rolled;

        public Integer getValue() {
            return this.value;
        }

        public void setValue(Integer value) {
            this.value = value;
        }

        public boolean wasRolled() {
            return this.rolled;
        }

        public void setRolled(boolean rolled) {
            this.rolled = rolled;
        }
    }
}

编辑注释中描述的方法,而不使用地图:

import java.util.Scanner;

public class RollDice {
    public static final String WELCOME = "[ Welcome to the game 12! Try to get the total sum of 12 by rolling 1-3 dices ] ";
    public static final String USER_INFO = "Enter which dice you want to roll [1,2,3] (Exit game with q): ";
    public static final String DICE_ALREADY_ROLLED = "Die already rolled, please roll a new die";
    public static final String ROUND_WON = "You rolled 12, you won the round !";
    public static final String ROUND_LOST = "Rounds lost, your die rolled more than 12. ";
    public static final String ROUND_TIED = "You neither lost, nor won, round tied.";
    public static final String INVALID_INPUT = "Please enter a number between 1-3 or Q to quit";
    public static final String THANKS_FOR_PLAYING = "Quitting game.. thanks for playing!";

    public static void main(String[] args) {
        int totalRounds = 1;
        int rolledDice, sum = 0;
        int roundsWon = 0, roundsLost = 0, roundsTied = 0;
        int dice1Value, dice2Value, dice3Value;
        boolean dice1Rolled = false, dice2Rolled = false, dice3Rolled = false;

        // Create Scanner to obtain data input from user.
        Scanner twelf = new Scanner(System.in);
        String input;

        System.out.println(WELCOME);

        while (true) {
            System.out.print(USER_INFO);
            input = twelf.nextLine();

            // The program should continue until the user chooses to cancel the game. Quit the game by pressing 'q' or 'Q'
            if(input.equalsIgnoreCase("q")){
                System.out.println(THANKS_FOR_PLAYING);
                break;
            }

            // check if user input is valid
            try{
                rolledDice = Integer.parseInt(input);
            }catch(NumberFormatException e){
                System.out.println(INVALID_INPUT);
                continue;
            }

            // The program must randomly find a value on the selected dice and then calculate the score. 
            switch(rolledDice){
                case 1:
                    if(dice1Rolled){
                        System.out.println(DICE_ALREADY_ROLLED);
                        continue;
                    } else{ 
                        dice1Value = (int) (Math.random() * 6) + 1;
                        sum += dice1Value;
                        dice1Rolled = true;
                        System.out.println("You rolled " + dice1Value + "; sum of dice: " + sum);
                        break;
                    }
                case 2:
                    if(dice2Rolled){
                        System.out.println(DICE_ALREADY_ROLLED);
                        continue;
                    } else{
                        dice2Value = (int) (Math.random() * 6) + 1;
                        sum += dice2Value;
                        dice2Rolled = true;
                        System.out.println("You rolled " + dice2Value + "; sum of dice: " + sum);
                        break;
                    }
                case 3:
                    if(dice3Rolled){
                        System.out.println(DICE_ALREADY_ROLLED);
                        continue;
                    } else{
                        dice3Value = (int) (Math.random() * 6) + 1;
                        sum += dice3Value;
                        dice3Rolled = true;
                        System.out.println("You rolled " + dice3Value + "; sum of dice: " + sum);
                        break;
                    }
                default:
                    System.out.println(INVALID_INPUT);
                    continue;
            }

            /* The program should also present the number of wins and the number of rounds lost. 
            The definition of profit is when the sum of the dice is 12 (regardless of the number of dice) and 
            the definition of loss is a sum exceeding 12 after all three dice have been rolled. 
            If the sum after three rolls is less than 12, there will be no profit or loss, but you go straight to the next round*/

            // you can move to next round in 2 rounds, by rolling 6 with 2 dice
            if(sum == 12){
                System.out.println(ROUND_WON);
                roundsWon++;
                totalRounds++;

                // reset dice rolled & sum
                dice1Rolled = false;
                dice2Rolled = false; 
                dice3Rolled = false;
                sum = 0;

                // show rounds won/lost/tied
                System.out.println("totalRounds: " + totalRounds + "; roundsWon: " + roundsWon + "; roundsTied: " + roundsTied + "; roundsLost: " + roundsLost);
                continue;
            }

            // If all 3 dice rolled, move to next round
            if(dice1Rolled && dice2Rolled && dice3Rolled){
                if(sum > 12){
                    roundsLost++;
                    System.out.println(ROUND_LOST);
                }
                if(sum < 12){
                    roundsTied++;
                    System.out.println(ROUND_TIED);
                }

                // reset dice rolled, move to next round
                dice1Rolled = false;
                dice2Rolled = false; 
                dice3Rolled = false;
                sum = 0;

                // show rounds won/lost/tied
                System.out.println("totalRounds: " + totalRounds + "; roundsWon: " + roundsWon + "; roundsTied: " + roundsTied + "; roundsLost: " + roundsLost);
            }
        }
    }
}

Instead of using switch statements, you may want to use a map to track if dice were rolled or not. rolledDiceMap will store your three dice, it has an Integer key and a Dice value.

For this I created a Dice class that has two fields:

  • value: the random value that gets rolled);
  • rolled: boolean flag, if this is true repeat the while loop until the user enters a good value and moves to the next round.

I tried to add some, hopefully, useful comments to the code below:

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class RollDice {
    public static final String WELCOME = "[ Welcome to the game 12! Try to get the total sum of 12 by rolling 1-3 dices ] ";
    public static final String USER_INFO = "Enter which dice you want to roll [1,2,3] (Exit game with q): ";
    public static final String WRONG_DIE_VALUE = "Please enter a good die value";
    public static final String DIE_ROLLED = "Die already rolled, please roll a new die";
    public static final String CONGRATULATIONS = "You rolled 12, congratulations !";
    public static final String GOOD_LUCK = "Good luck next time, your dice rolled: ";

    public static void main(String[] args) {
        int rounds = 1;
        int sum = 0;

        // Create Scanner to obtain data input from user.
        Scanner twelf = new Scanner(System.in);

        System.out.println(WELCOME);

        Map<Integer, Dice> rolledDiceMap = new HashMap();

        // Generate a key value pair for three dice e.g.: (1, Dice); (2, Dice); (3, Dice)
        for (int i = 1; i <= 3; i++) {
            rolledDiceMap.put(i, new Dice());
        }

        while (rounds <= 3) {
            System.out.print(USER_INFO);
            int rolledValue = twelf.nextInt();

            // check if user input is valid (user entered 1,2 or 3)
            if (rolledDiceMap.containsKey(rolledValue)) {
                Dice rolledDie = rolledDiceMap.get(rolledValue);

                // check if die was rolled, if yes, repeat round
                if(rolledDie.wasRolled()){
                    System.out.println(DIE_ROLLED);
                    // repeat round
                    continue;
                }

                // set rolled to true and assign a random value
                rolledDie.setRolled(true);
                int value = (int) (Math.random() * 6) + 1;
                rolledDie.setValue((int) (Math.random() * 6) + 1);

                sum += value;

                System.out.println("You rolled: " + value);
            } else {
                System.out.println(WRONG_DIE_VALUE);
                // repeat round
                continue;
            }

            // move to next round
            rounds++;
        }

        // print result
        if(sum == 12){
            System.out.println(CONGRATULATIONS);
        } else{
            System.out.println(GOOD_LUCK + sum);
        }
    }

    static class Dice {
        private Integer value;
        private boolean rolled;

        public Integer getValue() {
            return this.value;
        }

        public void setValue(Integer value) {
            this.value = value;
        }

        public boolean wasRolled() {
            return this.rolled;
        }

        public void setRolled(boolean rolled) {
            this.rolled = rolled;
        }
    }
}

Edit for the approach described in comments, without using map:

import java.util.Scanner;

public class RollDice {
    public static final String WELCOME = "[ Welcome to the game 12! Try to get the total sum of 12 by rolling 1-3 dices ] ";
    public static final String USER_INFO = "Enter which dice you want to roll [1,2,3] (Exit game with q): ";
    public static final String DICE_ALREADY_ROLLED = "Die already rolled, please roll a new die";
    public static final String ROUND_WON = "You rolled 12, you won the round !";
    public static final String ROUND_LOST = "Rounds lost, your die rolled more than 12. ";
    public static final String ROUND_TIED = "You neither lost, nor won, round tied.";
    public static final String INVALID_INPUT = "Please enter a number between 1-3 or Q to quit";
    public static final String THANKS_FOR_PLAYING = "Quitting game.. thanks for playing!";

    public static void main(String[] args) {
        int totalRounds = 1;
        int rolledDice, sum = 0;
        int roundsWon = 0, roundsLost = 0, roundsTied = 0;
        int dice1Value, dice2Value, dice3Value;
        boolean dice1Rolled = false, dice2Rolled = false, dice3Rolled = false;

        // Create Scanner to obtain data input from user.
        Scanner twelf = new Scanner(System.in);
        String input;

        System.out.println(WELCOME);

        while (true) {
            System.out.print(USER_INFO);
            input = twelf.nextLine();

            // The program should continue until the user chooses to cancel the game. Quit the game by pressing 'q' or 'Q'
            if(input.equalsIgnoreCase("q")){
                System.out.println(THANKS_FOR_PLAYING);
                break;
            }

            // check if user input is valid
            try{
                rolledDice = Integer.parseInt(input);
            }catch(NumberFormatException e){
                System.out.println(INVALID_INPUT);
                continue;
            }

            // The program must randomly find a value on the selected dice and then calculate the score. 
            switch(rolledDice){
                case 1:
                    if(dice1Rolled){
                        System.out.println(DICE_ALREADY_ROLLED);
                        continue;
                    } else{ 
                        dice1Value = (int) (Math.random() * 6) + 1;
                        sum += dice1Value;
                        dice1Rolled = true;
                        System.out.println("You rolled " + dice1Value + "; sum of dice: " + sum);
                        break;
                    }
                case 2:
                    if(dice2Rolled){
                        System.out.println(DICE_ALREADY_ROLLED);
                        continue;
                    } else{
                        dice2Value = (int) (Math.random() * 6) + 1;
                        sum += dice2Value;
                        dice2Rolled = true;
                        System.out.println("You rolled " + dice2Value + "; sum of dice: " + sum);
                        break;
                    }
                case 3:
                    if(dice3Rolled){
                        System.out.println(DICE_ALREADY_ROLLED);
                        continue;
                    } else{
                        dice3Value = (int) (Math.random() * 6) + 1;
                        sum += dice3Value;
                        dice3Rolled = true;
                        System.out.println("You rolled " + dice3Value + "; sum of dice: " + sum);
                        break;
                    }
                default:
                    System.out.println(INVALID_INPUT);
                    continue;
            }

            /* The program should also present the number of wins and the number of rounds lost. 
            The definition of profit is when the sum of the dice is 12 (regardless of the number of dice) and 
            the definition of loss is a sum exceeding 12 after all three dice have been rolled. 
            If the sum after three rolls is less than 12, there will be no profit or loss, but you go straight to the next round*/

            // you can move to next round in 2 rounds, by rolling 6 with 2 dice
            if(sum == 12){
                System.out.println(ROUND_WON);
                roundsWon++;
                totalRounds++;

                // reset dice rolled & sum
                dice1Rolled = false;
                dice2Rolled = false; 
                dice3Rolled = false;
                sum = 0;

                // show rounds won/lost/tied
                System.out.println("totalRounds: " + totalRounds + "; roundsWon: " + roundsWon + "; roundsTied: " + roundsTied + "; roundsLost: " + roundsLost);
                continue;
            }

            // If all 3 dice rolled, move to next round
            if(dice1Rolled && dice2Rolled && dice3Rolled){
                if(sum > 12){
                    roundsLost++;
                    System.out.println(ROUND_LOST);
                }
                if(sum < 12){
                    roundsTied++;
                    System.out.println(ROUND_TIED);
                }

                // reset dice rolled, move to next round
                dice1Rolled = false;
                dice2Rolled = false; 
                dice3Rolled = false;
                sum = 0;

                // show rounds won/lost/tied
                System.out.println("totalRounds: " + totalRounds + "; roundsWon: " + roundsWon + "; roundsTied: " + roundsTied + "; roundsLost: " + roundsLost);
            }
        }
    }
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文