1

我的头不再工作了。我必须尽快完成这个我怎样才能让这个 for 循环更短。

目前我有 4 个不同的 for 循环。我想把它们结合起来,只有一个。

Card[] cards = new Card[4*13];

void testCreateCards() {

  int k = 0;
  for (int suit = 0; suit <= 3; suit++) {               // for suit
    for (int value = 1; value <= 13; value++) {             // from Ace to King
      // build new card
      cards[k++] = new Card(suit, value);
    }
  }
}

void testDrawClubs() {
  int x = 0;
  int y = 0;
  for (int i = 0; i <= 12; i++) {
    cards[i].displayCard(x, y);
    x +=80;
  }
}

void testDrawDiamonds() {
  int x = 0;
  int y = 80;
  for (int i = 13; i <= 25; i++) {
    cards[i].displayCard(x, y);
    x +=80;
  }
}

void testDrawHearts() {
  int x = 0;
  int y = 160;
  for (int i = 26; i <= 38; i++) {
    cards[i].displayCard(x, y);
    x +=80;
  }
}
void testDrawSpades() {
  int x = 0;
  int y = 240;
  for (int i = 39; i <= 51; i++) {
    cards[i].displayCard(x, y);
    x +=80;
  }
}
4

1 回答 1

5

您可以使用模算术直接计算 x 和 y,因为i % 13为您提供 x 坐标并i / 13为您提供 y 坐标:

void testDrawCards() {
    for (int i = 0; i < 52; i++) {
        int x = i % 13;
        int y = i / 13;
        cards[i].displayCard(x * 80, y * 80);
    }
 }
于 2012-12-22T12:08:25.680 回答