玩家之间有一场比赛,第一个得到21分的玩家获胜。当两个玩家在相同的掷骰子数上达到 21 时,就会出现平局。
随着骰子的滚动,积分相加。
其格式应按如下方式完成。
*游戏 1 *
Roll Player 1 Player 2
1 5 4
2 7 10
3 12 14
4 13 16
5 19 21
player 2 wins!
下面的代码是我到目前为止尝试过的。
我被困住了,因为我不知道如何创建像上面这样的图表。
如果我尝试在 while 循环内制作图表,它将重复制作图表。
如果我尝试在 while 循环之外(即在 while 循环之后)制作图表,它将
仅当其中一名玩家达到第 21 点时才执行。
谁能帮我如何制作这段代码?
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("RolltPlayer 1tPlayer 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("%dt%dt%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
如果你想每圈打印一个输出,你需要在while循环内打印。下面是具有此类功能的示例代码段。当然,这不是一个完整的程序,可以使用一些格式化爱。
int sum1 = 0;
int sum2 = 0;
int round = 1;
while(sum1 < 21 && sum2 < 21) { // not sure if you noticed this bug in your code..
sum1 += rand.nextInt(6) + 1;
sum2 += rand.nextInt(6) + 1;
System.out.println("Round " + round + " " + sum1 + " " + sum2);
round++;
}