我一直坐在这里试图了解这段代码是如何运行的。我了解(或认为我了解)布尔运算符在 if 语句中的工作方式,但显然我不了解。代码是:
public class Exercise_6_24 {
public static void main(String[] args) {
final int NUMBER_OF_CARDS = 52;
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9",
"10", "Jack", "Queen", "King"};
// found indicates whether a suit has been picked
boolean[] found = new boolean[4];
// Count the number of picks
int numberOfPicks = 0;
// Count occurrence in each suit
int count = 0;
while (count < 4) {
numberOfPicks++;
int index = (int)(Math.random() * NUMBER_OF_CARDS);
if (!found[index / 13]) {
found[index / 13] = true;
count++;
String suit = suits[index / 13];
String rank = ranks[index % 13];
System.out.println(rank + " of " + suit);
}
}
System.out.println("Number of picks: " + numberOfPicks);
}
}
这基本上是那些选卡问题之一。我感到困惑的部分是 while 循环中的第一个 if 语句。在循环之前,找到的布尔数组中的所有槽都设置为 false。然而,while 循环中的 if 语句正在测试找到的布尔数组是否设置为 true,如果为 true,则运行 if 语句中的代码。它不应该运行,但它会运行。当我在那里设置断点时,我看到布尔数组槽从 false 变为 true 以使 if 语句中的代码运行。
我真的不明白这是怎么回事。有人可以向我解释这是怎么回事吗?
谢谢!