如何让这个for循环缩短?

时间:2012-12-22 12:05:40

标签: java processing

我的头不再工作了。我必须完成这个a.s.a.p. 我怎样才能让这个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;
  }
}

1 个答案:

答案 0 :(得分:5)

您可以使用modular arithmetic直接计算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);
    }
 }