public class BlackJack {
public static void main(String args[]) {
String input;
char reDo;
Scanner keyboard = new Scanner (System.in);
Random random = new Random();
int card1 = random.nextInt(10) + 1;
int card2 = random.nextInt(10) + 1;
int card = random.nextInt(10) + 1;
int total1 = card1 + card2;
int total2 = total1 + card;
System.out.print("First cards: " + card1 + ", " + card2 + "\n");
System.out.print("Total: " + total1 + "\n");
boolean loop = true;
while (loop) {
System.out.print("Do you want another card? (y/n): ");
input = keyboard.nextLine();
reDo = input.charAt(0);
if (reDo == 'y' || reDo == 'Y') {
System.out.print("Card: " + card + "\n");
System.out.print("Total: " + total2 + "\n");
} else if (reDo == 'n' || reDo == 'N') {
loop = false;
}
}
}
}
输出如下:
第一张牌:8,3 总计:11
你想要另一张卡吗? (是/否):y
卡片:7
总计:18
你想要另一张卡吗? (是/否):y
卡片:7
总计:18
你想要另一张卡吗? (y / n):n
我希望能够在循环中生成新的随机卡,显示重复总计,并停止程序。我无法理解的问题是如何使用random.nextInt工具并能够更方便地重用它。目前它卡住了card1,card2,card,total1和total2。如果我可以制作它们以便我可以更轻松地访问它们,那么我认为编写程序会更容易。问题是我无法理解如何在while循环中重复random.nextInt。
答案 0 :(得分:0)
首先将所有牌放入牌组中。
然后在0和卡组中的卡数之间生成一个随机数。
如果deck是一个ArrayList(例如),你可以做
import java.util.*;
public class Main
{
public static void main(String[] args)
{
List<Card> deck = new ArrayList<Card>();
deck.add(new Card(1));
deck.add(new Card(3));
deck.add(new Card(7));
deck.add(new Card(10));
Random randomGenerator = new Random();
System.out.println("Deck 1 tests");
// draw 3 cards:
for (int i = 0; i < 3; i++)
{
int randomCard = randomGenerator.nextInt(deck.size());
Card card = deck.remove(randomCard);
System.out.println("Removed a(n) "+card);
}
// you could also do
List<Card> deck2 = new ArrayList<Card>();
deck2.add(new Card(1));
deck2.add(new Card(7));
deck2.add(new Card(3));
deck2.add(new Card(10));
Collections.shuffle(deck2);
System.out.println("Deck 2 tests");
// draw 3 cards:
for (int i = 0; i < 3; i++)
{
Card card = deck2.remove(0);
System.out.println("Removed a(n) "+card);
}
}
}
class Card {
public Card(int i)
{
blackJackValue = i;
}
public int blackJackValue;
public String toString() {
return String.valueOf(blackJackValue);
}
}