java - 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");
}
}
}
解决方案
几个问题
- 你想测试它
sum1
并且sum2
小于 21不是!=
+=
你不应该使用=+
- 引入了一个柜台
注意
我认为你的逻辑是不正确的,但如果两者都在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
推荐阅读
- r - r data.table::dcast 交叉产品在大型数据集上失败
- windows-10 - Inno setup 无法在 Windows 10 中创建桌面图标
- julia - 如何修复solveODE中的“dt <= dtmin.Aborting”错误
- c# - 如何在运行时设置类型时使用 Queryable.Where?
- laravel - 如何修复 Telegram Webhook 响应中的“来自 webhook 的错误响应:301 Moved Permanently”?
- laravel - 无法让 laravel 自定义存储库工作
- php - 使用 RewriteRule 名称 .htaccess 限制 url 重定向
- python-3.x - 在子进程中访问字符串值时 Python 冻结
- neural-network - 神经网络和无序输入数据
- php - 我的 JSON 数组需要如何格式化才能遍历这个 $.each?