我正在创建一个简单的Blackjack java程序,我很难接受while循环输入验证。当要求用户绘制卡片时,他/她可以选择:(y / n)以及是否想要再次播放。我的问题是,当我被提示画一张卡片而我选择了y时,那个角色只会提示画一张卡片......但似乎任何角色都会这样做。如果我想再次播放,播放循环也是如此。此外,当我被提示再次播放时,我想返回到while循环的开头,但我似乎无法调用该函数。我需要帮助!这是我的代码:
import java.util.Random;
import java.util.Scanner;
public class BlackJack
{
public static void main(String[] args)
{
char play = 'y';
char drawAgain;
int card1, card2;
int nextCard = 0;
Scanner keyboard = new Scanner(System.in);
Random number = new Random();
while (play != 'n')
{
card1 = number.nextInt(10) + 1;
card2 = number.nextInt(10) + 1;
System.out.print("First cards: ");
System.out.println(card1 + ", " + card2);
int cardTotal = card1 + card2;
System.out.println("Total: " + cardTotal);
System.out.print("Draw again? (y/n): ");
drawAgain = keyboard.next().charAt(0);
while (drawAgain != 'n')
{
int card3 = number.nextInt(10) + 1;
System.out.println("Card: " + card3);
cardTotal += card3;
System.out.println("Total: " + cardTotal);
if (cardTotal <= 21) {
System.out.print("Draw Again? (y/n): ");
drawAgain = keyboard.next().charAt(0);
}
if (cardTotal > 21) {
System.out.println("Bust");
System.out.print("Would you like to play again? (y/n): ");
play = keyboard.next().charAt(0);
}
}
}
}
}
答案 0 :(得分:0)
此代码存在一些问题。
以下解决了这些问题。这应该是你想要的。
import java.util.Random;
import java.util.Scanner;
public class BlackJack
{
public static char getValidInput(){
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
while(!input.equals("yes") || !input.equals("no")){
System.out.println("please input yes or no");
input = keyboard.next();
}
return input.charAt(0);
}
public static void main(String[] args)
{
char play = 'y';
char drawAgain;
int card1, card2;
int nextCard = 0;
Random number = new Random();
while (play != 'n')
{
card1 = number.nextInt(10) + 1;
card2 = number.nextInt(10) + 1;
System.out.print("First cards: ");
System.out.println(card1 + ", " + card2);
int cardTotal = card1 + card2;
System.out.println("Total: " + cardTotal);
System.out.print("Draw again? (y/n): ");
drawAgain = getValidInput();
while (drawAgain != 'n')
{
int card3 = number.nextInt(10) + 1;
System.out.println("Card: " + card3);
cardTotal += card3;
System.out.println("Total: " + cardTotal);
if (cardTotal <= 21) {
System.out.print("Draw Again? (y/n): ");
drawAgain = getValidInput();
}else{ //if (cardTotal > 21) {
System.out.println("Bust");
drawAgain ='n';
}
}
play = getValidInput();
}
}
}