0
public class NewDeck {

    public static void main(String[] args){

        String[] suits = new String[] {"Clubs", "Diamonds", "Spades", "Hearts"};

        String[] faces = new String[] {"Ace", "King", "Queen", "Jack"};

        String[][] deck = new String[][] {{},{}};

        int a = 0;
        int b = 0;

        for(String x: suits){

            a ++;

            for(String y: faces){


                deck[a][b] = {{x, y}};  // THIS IS THE LINE I NEED HELP WITH

                b++;

        System.out.println(deck);

            }

        }

    }

}

我期望打印的是:

{{"Clubs, "Ace"}{"Diamonds", "Ace"}{"Spades", "Ace"}{"Hearts", "Ace"}
 {"Clubs, "King"}{"Diamonds", "King"}{"Spades", "King"}{"Hearts", "King"}
 {"Clubs, "Queen"}{"Diamonds", "Queen"}{"Spades", "Queen"}{"Hearts", "Queen"}
 {"Clubs, "Jack"}{"Diamonds", "Jack"}{"Spades", "Jack"}{"Hearts", "Jack"}

当我想打印时:

deck[4][0]

我希望它打印:

"Clubs"

我知道我非常接近它只有一条线我相信我做错了,所以我评论了导致问题的那条线。如果有人知道要放入什么而不是:

deck[a][b] = {{x, y}};

将不胜感激。感谢您提前提供任何答案

4

3 回答 3

2
public static void main(String args[]) {
    String suits[] = new String[] {"Clubs", "Diamonds", "Spades", "Hearts"};
    String faces[] = new String[] {"Ace", "King", "Queen", "Jack"};
    String deck[][] = new String[suits.length * faces.length][2];

    int i=0;

    for (String suit : suits) {
        for (String face : faces) {
            deck[i][0] = suit;
            deck[i][1] = face;
            i++;
        }
    }
}
于 2013-08-03T10:24:12.520 回答
1
deck[a][b] = {{x, y}};

用这样的东西替换它:

deck[index][0]=x;
deck[index][1]=y;

deck[4][0]不会产生正确的结果。请记住,数组的元素索引从 0 开始,到 array-size-1 结束。

System.out.println(deck);您将无法通过简单地打印数组本身来打印数组的值。
上面的语句将简单地打印数组对象的哈希码。请记住,它是一个数组,而不是 List 或 Set。您需要遍历数组并打印其中的元素。

于 2013-08-03T10:29:27.697 回答
0

我认为您将需要一些Card课程。

public class NewDeck {
  public static class Card {
    public final String suit;
    public final String face;
    public Card(String suit, String face) {
      this.suit = suit;
      this.face = face;
    }
    public String toString() {
      return "{\"" + suit + "\", \"" + face + "\"}";
    }
  }
  public static void main(String[] args) {
    String[] suits = new String[] {"Clubs", "Diamonds", "Spades", "Hearts"};
    String[] faces = new String[] {"Ace", "King", "Queen", "Jack"};

    Card[][] deck = new Card[suits.length][faces.length];

    int a = 0;
    int b = 0;
    for(String x: suits){
      b = 0;
      for(String y: faces){
        deck[a][b] = new Card(x, y);
        b++;
      }
      a++;
    }
  }
}
于 2013-08-03T11:01:16.650 回答