这是代码:
基本上,这段代码打印出 52 张花色 + 等级的牌。
package javaapplication52;
public class JavaApplication52 {
public static void deck() {
String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };
String[] rank = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack",
"Queen", "King", "Ace" };
// avoid hardwired constants
int SUITS = suit.length;
int RANKS = rank.length;
int N = SUITS * RANKS;
// initialize deck
String[] deck = new String[N];
for (int i = 0; i < RANKS; i++) {
for (int j = 0; j < SUITS; j++) {
deck[SUITS * i + j] = rank[i] + " of " + suit[j];
}
}
// shuffle
for (int i = 0; i < N; i++) {
int r = i + (int) (Math.random() * (N - i));
String t = deck[r];
deck[r] = deck[i];
deck[i] = t;
}
// print shuffled deck
for (int i = 0; i < N; i++) {
System.out.println(deck[i]);
}
}
public static void main(String[] arg) {
JavaApplication52 d = new JavaApplication52();
d.deck();
}
}
对我来说毫无意义的代码
deck[SUITS * i + j] = rank[i] + " of " + suit[j]
我不明白的是,为什么他们乘以 SUITS 乘以我然后添加 j。令人困惑的是 SUITS(等于 4),乘以 i(等于 13),然后加上 j(其(值为 4),根本不等于 52。所以请解释一下,这个函数是如何工作的。