gpt4 book ai didi

java - 如何以新值退出 while 循环?

转载 作者:太空宇宙 更新时间:2023-11-04 11:06:01 25 4
gpt4 key购买 nike

对于我的一项作业,我们应该首先生成一个 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

最佳答案

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

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) ;

关于java - 如何以新值退出 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46480892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com