【发布时间】:2017-09-29 11:08:59
【问题描述】:
对于我的一项任务,我们应该首先生成一个介于 1 和 13 之间的随机数,然后我们询问用户是否想绘制另一个数字。如果他们这样做,我们应该在 1-13 内添加另一个随机数而不超过 21。我坚持的是如何在添加 1 个新随机数后退出 while 循环并询问用户是否愿意添加另一个。我尝试使用 break;这是我目前所拥有的:
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
【问题讨论】:
-
将询问放在循环中。逻辑是 -> 同时,玩家选择卡(是继续,不中断),随机卡,如果堆栈超过 21 中断,则将新卡添加到堆栈。
标签: java while-loop do-while