首页 > 解决方案 > A dice game between two players. The player who gets 21 first wins

问题描述

There is a game between two players, and the first player who gets 21 points wins. when both players reach 21 on the same number of rolls, there is a tie.

The points are added up as the dices are rolled.

The format of this should be done as follows.

* GAME 1 *

 Roll              Player 1         Player 2

1               5                 4

2               7                 10

3               12                14

4               13                16

5               19                21
  player 2 wins!

The code below is what I've tried so far.

I'm stuck because I have no idea how to create a chart like the one above.

If I try to make the chart inside the while loop, it will repeatedly make the chart.

If I try to make the chart outside the while loop, which is after the while loop, it will

execute only when one of the players reach points 21.

Can anyone help me out how to make this code?

 import java.util.*;


public class Dice {
public static void main(String[] args) {

  Scanner input = new Scanner(System.in);
  Random rand = new Random();

  System.out.println("How many games do you want to play?");
  int games= input.nextInt();

  System.out.println(" *** Game 1 *** ");
  int sum1=0;
  int sum2=0;
  while (sum1!=21&&sum2!=21){
     int roll1 = rand.nextInt(6) + 1;
     int roll2 = rand.nextInt(6) + 1;

     sum1=+roll1;
     sum2=+roll2;
  }

  if(sum1>sum2){

     System.out.println("player 1 wins");
  }

  else if(sum1<sum2){
     System.out.println("player 2 wins");
     }

   }

}

标签: java

解决方案


几个问题

  1. 你想测试它sum1并且sum2小于 21不是 !=
  2. +=你不应该使用=+
  3. 引入了一个柜台

注意 我认为你的逻辑是不正确的,但如果两者都21同一个范围内会发生什么?

    System.out.println(" *** Game 1 *** ");
    int sum1=0;
    int sum2=0;
    int rollNumber = 1;
    System.out.println("Roll\tPlayer 1\tPlayer 2");
    while (sum1 < 21 && sum2 < 21){
         int roll1 = rand.nextInt(6) + 1;
         int roll2 = rand.nextInt(6) + 1;

         sum1 += roll1;
         sum2 += roll2;

         if (sum1 > 21) sum1 = 21;
         if (sum2 > 21) sum2 = 21;

         System.out.format("%d\t%d\t%d%n", rollNumber++, sum1, sum2);
    }

    if(sum1>sum2){

         System.out.println("player 1 wins");
    }
    else if(sum1<sum2){
         System.out.println("player 2 wins");
    }

    }

输出

 *** Game 1 *** 
Roll    Player 1    Player 2
1   5   4
2   4   5
3   2   3
4   3   1
5   3   3
6   2   3
7   5   6
player 2 wins

推荐阅读