gpt4 book ai didi

java - 使用循环的初学者二十一点游戏

转载 作者:行者123 更新时间:2023-12-01 23:14:55 29 4
gpt4 key购买 nike

我正在尝试为学校创建一个二十一点程序,但我不明白为什么在我拿到前两张牌后要求另一张牌后我的程序不断重新开始。任何帮助都会很棒。我的所有代码如下。

import java.util.Scanner;
import java.util.*;

public class BlackjackGame {

public static void main(String[] args) {

String anotherCard, playAgain = "y", ctn;
int nextCard, card1, card2, dCard1, dCard2;
int cardTotal = 0, dTotal = 0;

Scanner keyboard = new Scanner(System.in);

Random random = new Random();

// Begin dealing the players first two cards

while (playAgain == "y")
{
//dealers first two random cards
dCard1 = random.nextInt(10) + 1;
dCard2 = random.nextInt(10) +1;

//players first two random cards and card total
card1 = random.nextInt(10) + 1;
card2 = random.nextInt(10) + 1;
cardTotal = card1 + card2;

//Dealers two card total and display only one dealer card
dTotal = dCard1 + dCard2;
System.out.println("Dealer shows: " + dCard1);

//Display players first two cards & card total
System.out.println("First Cards: " + card1 + ", " +card2);
System.out.println("Total: "+ cardTotal);

System.out.print("Another Card (y/n)?: ");
anotherCard = keyboard.nextLine();

while (anotherCard == "y")
{
nextCard = random.nextInt(10) + 1;
cardTotal += nextCard;
System.out.println("Card: " + nextCard);
System.out.println("Total: " + cardTotal);

if (cardTotal > 21)
{
System.out.println("You busted, Dealer Wins");
System.out.println("Do you want to play again? (y/n): ");
playAgain = keyboard.nextLine();
}
if (cardTotal < 21)

System.out.print("Another Card (y/n)?: ");
anotherCard = keyboard.nextLine();
if (anotherCard == "n")
System.out.print("Press c to continue dealers cards");
ctn = keyboard.nextLine();


while (ctn == "c" && dTotal < 17)
{
nextCard = random.nextInt(10) + 1;
dTotal += nextCard;

if (dTotal > 21)
{
System.out.println("Dealer Busts, You Win!");
System.out.println("Play Again? (y/n): ");
playAgain = keyboard.nextLine();
if (playAgain.equalsIgnoreCase("y"))
playAgain = "y";
else
System.exit(0);
}

}

}

}
}
}

最佳答案

这个表达式:

if (playAgain == "y")

永远不会为真,因为==运算符仅在两个操作数是相同对象时才为真。要比较字符串的,请使用equals():

if (playAgain.equals("y"))
<小时/>

别难过。问题在于语言 - 使用这样的 == 运算符是一个愚蠢的选择。这里很大一部分问题都表明了这个问题的根源。

关于java - 使用循环的初学者二十一点游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21394716/

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