我还是新手,我在这个项目中遇到了困难。我需要洗牌并获得前四张牌并计算四张牌的总和。到目前为止,我已经完成了这项任务。现在我的问题是我需要重复这个方法,直到我得到24的总和。我很难知道如何循环该方法。这是我到目前为止所做的代码:
public class cards
{
public static void main(String[] args)
{
int[] deck = new int[52];
String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
int rankedVal[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
int tot = 0;
if (tot != 24){
//Initialize cards
tot = 0;
for (int i = 0; i < deck.length; i++)
deck[i] = i;
//Shuffle cards
for (int i = 0; i < deck.length; i++)
{
int index = (int)(Math.random() * deck.length);
int temp = deck[i];
deck[i] = deck[index];
deck[index] = temp;
}
//Display first four
for (int i = 0; i < 4; i++)
{
String suit = suits[deck[i] / 13];
String rank = ranks[deck[i] % 13];
System.out.println("Card number " + deck[i] + ": " + rank + " of " + suit);
}
//find the total
for (int i = 0; i<4;i++){
tot = tot + rankedVal[deck[i] % 13];
}
System.out.println("Total Hand = " + tot);
}
}
}
答案 0 :(得分:1)
我将使用更通用的代码,因为不同的表示适合不同的程序员,但这应该适用于任何事情:
int sum = 0;
While (sum != 24)
{
Shuffle();
sum = deck[0].value + deck[2].value + deck[3].value + deck[4].value;
}
如果你制作牌组并在洗牌时在牌组之间进行交换会更好,并且牌里面有一个整数值。初始化一次然后它们都交换对象。这是Java,不是吗?
答案 1 :(得分:1)
如果没有制作扰流板,您可以在while循环中使用条件,直到达到24,如:
do
{
// Get 4 cards and add sum.
} while (sum < 24);
另外你需要检查一下你的卡片用完了,所以改进了:
int cardsUsed = 0
do
{
// Get 4 cards and add sum.
cardsUsed += 4;
} ((sum < 24) or (cards_used >= 52));
答案 2 :(得分:1)
这就是为什么你应该学习如何使用方法和子程序。如果您使用的是Java,那么您首先应该先了解一下面向对象编程。如果您不了解OOP,我不会推荐Java作为初学者语言。也许去C或Python。
public class cards
{
int[] deck = new int[52];
String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
int rankedVal[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
void init() {
// initialise logic
for (int i = 0; i < deck.length; i++)
deck[i] = i;
}
void shuffleCards() {
for (int i = 0; i < deck.length; i++) {
// Shuffle logic
}
}
void displayFirstFour() {
// display logic
}
int sumFirstFour() {
int sum = 0;
// logic to sum first four cards
return sum;
}
public static void main(String[] args)
{
init();
int total = 0;
// LOOP. NOT 'if' . 'if' simply tests condition once and moves on
// loop tests condition continually until true
while(total != 24) {
//Shuffle cards
shuffleCards();
//Display first four
displayFirstFour();
total = sumFirstFour();
}
System.out.println("Total Hand = " + total);
}
}