如何以新值退出while循环?

时间:2017-09-29 02:26:04

标签: java while-loop do-while

对于我的一个作业,我们应该首先生成1到13之间的随机数,然后我们询问用户是否想要绘制另一个数字。如果他们这样做,我们应该在1-13之内添加另一个随机数而不超过21.我坚持的是如何在添加1个新随机数后退出while循环并询问用户是否愿意再添一个。我尝试过休息;这就是我到目前为止所做的:

int randCard = 1 + (int) (Math.random() * ((13 - 1) + 1));
    int playerHand = 0 + randCard;
    System.out.println("START GAME #" + gameNum);
    System.out.println("Your card is a " + randCard + "!");
    System.out.println("Your hand is: " + playerHand);
    System.out.println("\n1. Get another card");
    System.out.println("2. Hold hand");
    System.out.println("3. Print statistics");
    System.out.println("4. Exit");
    System.out.print("\nChoose an Option: ");
    int selectedOption = menuOptions.nextInt();

 if (selectedOption == 1) {

             do {
                 int newRandCard = 1 + (int) (Math.random() * ((13 - 1) + 1));

                 System.out.println("Your card is a " + newRandCard + "!");
                 System.out.println("Your hand is: " + (playerHand + newRandCard));

                 playerHand = (playerHand + newRandCard);


                break;

             }
                 while (playerHand <= 21) ;

////////IDEALLY IT SHOULD PRINT LIKE THIS//////
Your card is a 4!
Your hand is: 4
1. Get another card
2. Hold hand
3. Print statistics
4. Exit
Choose an option: 1
Your card is a 9!
Your hand is: 13
1. Get another card
2. Hold hand
3. Print statistics
4. Exit

3 个答案:

答案 0 :(得分:0)

如果您只需要添加一次随机数,那么再次为用户提供菜单选项

System.out.println("START GAME #" + gameNum);
int randCard = 1 + (int) (Math.random() * ((13 - 1) + 1));
System.out.println("Your card is a " + randCard + "!");
int playerHand = 0 + randCard;
System.out.println("Your hand is: " + playerHand);
do {
  System.out.println("1. Get another card");
  System.out.println("2. Hold hand");
  System.out.println("3. Print statistics");
  System.out.println("4. Exit");
  System.out.println("Choose an Option: ");
  int selectedOption = menuOptions.nextInt();

  if (selectedOption == 1) {
      randCard = 1 + (int) (Math.random() * ((13 - 1) + 1));
      System.out.println("Your card is a " + newRandCard + "!");
      System.out.println("Your hand is: " + (playerHand + newRandCard));
      playerHand = (playerHand + randCard);
  }
   ...other options to select
} while (playerHand <= 21) ;

答案 1 :(得分:0)

您可以将代码更改为以下内容以循环,直到用户进行1以外的选择。

if (selectedOption == 1) {
     do {
         ...
     } while (playerHand <= 21 && selectedOption == 1);

答案 2 :(得分:0)

如果您只想绘制一张卡片,请不要使用do-while循环。只需使用do-while中的内容(不包括休息时间)。

如果你想在用户告诉你之前绘制牌,那么创建一个布尔变量并将其用作执行周期的条件,并在每个周期结束时读取它。