该程序的目的是创建一个随机数生成器,并选择编号为 1-11 的牌(11 是 Ace)。游戏规则并不重要,重要的是完成的工作程序,我不需要花色、金钱或高分表。
我尝试创建一个卡片生成器,每次需要时都会生成一个随机卡片值,但失败了。正如您将在代码中看到的, int card1 = 1 +r.nextInt();每次都返回相同的值。如果它为card1调用4,则所有 future 的card1也将是4。这不是我在创建int值1-11 inc时想到的。我本来希望card1每次都会返回一个随机值。
接下来,我尝试将卡片总数和 newCard1 添加到当前 int,但失败了。这也无法按预期工作。
这是我迄今为止尝试过的代码,请记住,当您向我解释更正时,我是一年级学生,几乎没有任何基础知识:
import java.util.Random;
import java.util.Scanner;
class blackj
{
public static void main(String[] args)
{
Random r = new Random();
Scanner keyboard = new Scanner(System.in);
String name;
boolean playing = true;
boolean notPlaying = true;
int card1 = 1 + r.nextInt(11);
int card2 = 1 + r.nextInt(11);
int dcard1 = 1 + r.nextInt(11);
int dcard2 = 1 + r.nextInt(11);
int ptotal = card1+card2;
int dtotal = dcard1+dcard2;
int pcurrent = ptotal+card1;
int dcurrent =dtotal+dcard1;
{
System.out.println("Welcome to Blackjack ! " );
System.out.println("Score as close to 21 without going over to win ");
System.out.println("What is your name?");
name = keyboard.nextLine();
System.out.println("Hello " + name);
System.out.println("Let's play some BlackJack!");
System.out.println("The dealer shows: \n\t\t" +dcard1 );
System.out.println("Your first card is: \n\t\t " +card1 );
System.out.println("Your second card is: \n\t\t" +card2 );
System.out.println("Giving you a grand total of: " +ptotal );
while (playing)
{
System.out.println("Would you like to (H)it or (S)tick?");
Scanner hit1 = new Scanner(System.in);
String a = hit1.nextLine();
if(a.equals("s"))
{
System.out.println("You stick at " );
System.out.println("Now it's the dealers turn\n Dealer must draw until 17");
}
if(a.equals("h"))
{
System.out.println("Your next card is " +card2 );
System.out.println("Giving you a new total of "+pcurrent );
if ((pcurrent >=22))
System.out.println("You Busted! \nSorry! you lose");
}
else
{
System.out.println("Please press H or S");
}
}
}
}
}
正如你所看到的,我还没有到达经销商部分。
最佳答案
在 while 循环中再次调用 random:
int newCard = 1 + r.nextInt(11);
这会将变量设置为新的随机值(如果您需要重置原始卡变量,您也可以这样做)。然后确保根据这张新的随机卡检查用户的输入。
完成此操作后,您可能需要查看 code review有关构建程序的一些提示。
关于java - 简单的二十一点游戏;出了差错 : help needed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29066996/