当我运行我的程序时,它完全跳过第二个while循环( while(getCard ==&#34; y&#34;))并且不循环第一个while循环,即使< em> playAgain =&#34; y&#34; 。它在程序开始时进入循环,但退出整个程序,没有错误信息,在&#34之后;你想再玩一次吗? (y / n):&#34; 得到解答。
这是星期二午夜时分,我无法弄清楚出了什么问题。
import java.util.Scanner;
import java.util.Random;
public class BlackjackGame
{
public static void main(String[] args)
{
//declare variables
int card1, card2, newCard, total = 0;
String getCard, playAgain = "y";
//set up Scanner and Random objects
Scanner keyboard = new Scanner (System.in);
Random rand = new Random ();
while (playAgain == "y")
{
//Draw two cards and calculate total
card1 = rand.nextInt(11) + 1;
card2 = rand.nextInt(11) + 1;
total = card1 + card2;
//Display cards and total
System.out.println("First cards: " + card1 + ", " + card2);
System.out.println("Total: " + total);
//Ask user if they want another card
System.out.print ("Do you want another card? (y/n): ");
getCard = keyboard.nextLine();
while (getCard == "y")
{
//Draw another card
newCard = rand.nextInt(10) + 1;
total += newCard;
//Display new card and new total
System.out.println ("Card: " + newCard);
System.out.println ("Total: " + total);
if (total > 21)
{
System.out.println ("Bust!");
getCard = "n";
}
else if (total == 21)
{
System.out.println ("Blackjack!");
getCard = "n";
}
else
{
System.out.print ("Do you want another card? (y/n): ");
getCard = keyboard.nextLine();
}
}
//Ask if user wants to play again.
System.out.print ("Would you like to play again? (y/n): ");
playAgain = keyboard.nextLine();
}
}
}