-5

我一直坐在这里试图了解这段代码是如何运行的。我了解(或认为我了解)布尔运算符在 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 语句中的代码运行。

我真的不明白这是怎么回事。有人可以向我解释这是怎么回事吗?

谢谢!

4

2 回答 2

3

你不是在测试它是否是真的,你是在测试它是否是假的。这个说法:

!found[index / 13]

方法:

found[]at的位置index / 13,测试是否不是 true

!是一个布尔补码,所以它反转了值。如果found[index / 13]is false,则!found[index / 13]is true,因此该if语句将运行。

于 2012-12-18T04:44:41.590 回答
2

if (!found[index / 13]) {

将其读作“如果未找到此卡。它正在检查该值是否为false,因为只有这样 !found[..] 才会为真,并且该if块将执行。

于 2012-12-18T04:44:25.080 回答