我正在寫一個程序,做一個卡技巧,但首先我必須弄清楚如何處理3行7張卡。我無法弄清楚爲什麼當我運行我的程序時,它只輸出所有卡的一個數字,以及如何讓它打印出卡的名稱。我可以用PrintCard()函數打印52張獨特的卡片,但在使用Deal()時不能打印,我不知道爲什麼會有任何幫助。謝謝。Java卡處理程序
這是目前我的代碼:
import java.util.Random;
public class testing {
public static void main(String[] args) {
testing cs = new testing();
int [] deck = new int [52];
int [] [] play = new int [7] [3];
cs.BuildDeck (deck);
cs.Deal(deck, play);
}
public static void BuildDeck(int deck[]) {
int[] used = new int[52];
int card = 0;
int i = 0;
/*
* Generate cards until the deck is full of integers
*/
while (i < deck.length) {
/*
* generate a random number between 0 and 51
*/
Random random1 = new Random();
card = (random1.nextInt(52) % 52);
/*
* Check the used array at the position of the card. If 0, add the card and set the used location
* to 1. If 1, generate another number
*/
if (used[card] == 0) {
used[card] = 1;
deck[i] = card;
i++;
}
}
}
public static void PrintCard(int card) {
int rank = (card % 13);
int suit = (card/13);
String[] suits = {"Clubs", "Hearts", "Diamonds", "Spades"};
String[] ranks = {"King", "Ace", "2", "3", "4", "5", "6",
"7", "8", "9", "10", "Jack", "Queen"};
System.out.println(ranks[rank] + " of " + suits[suit]);
}
public static void Deal(int deck[], int play[][]) {
int card = 0;
System.out.println ("\n Column 0 Column 1 Column 2");
System.out.println ("=======================================================\n");
for (int row = 0; row < play.length; row++) {
for (int col = 0; col < play [row].length; col++) {
play[row][col] = deck[card++];
System.out.print(" " + play[row][col] + " ");
}
System.out.println();
}
}
}
更大的計劃:http://pastebin.com/99tLpVjM
雷內說什麼。但是:你的建造方式+洗牌是不理想的,因爲它不能保證完成。 'Collections.shuffle(Arrays.asList(array));'的行會是更好的解決方案。 – tim 2012-03-28 11:16:30
代碼批判:從不使用主列中的'i'。 while循環中的'random1'只能初始化一次。卡應該在while循環中聲明,因爲它不在外部使用。 Deal中的'row,col,card'應該在for循環中聲明。 – 2012-03-28 11:18:29
方法以大寫字母開頭! – mishadoff 2012-03-28 11:26:33