在创建对象时,不能将String转换为String []

时间:2016-06-30 09:45:48

标签: java

我已经查看了多个主题,但仍然无法理解我做错了什么。诚实的帮助表示赞赏。

在我的代码中,我试图创建一个卡片组并将值初始化为每个阵列52个插槽。但是,在尝试这样做时,我不断收到错误String无法转换为String []。

我做错了什么?

public class Card {
static String[] rank = {"2","3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
    static String[] suit = {"Spades","Hearts", "Clubs", "Diamonds"};
    static Card[] deck = new Card[52];

    public Card(String[] rank, String[] suit)
    {
        this.rank = rank;
        this.suit = suit;
    }

  public static void main(String[] args) {
        // TODO code application logic here


    for(int x = 0; x<deck.length; x++)
    {
        Card cards = new Card(rank[x%13], suit[x/13]);

    }

4 个答案:

答案 0 :(得分:4)

new Card(rank[x%13], suit[x/13])您正在向构造函数提供String个对象,而期望String[]个对象

以下可能是您案例中的解决方案。

String rank, suit;    
static String[] ranks = {"2","3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
static String[] suits = {"Spades","Hearts", "Clubs", "Diamonds"};
static Card[] deck = new Card[52];

public Card(String rank, String suit)
{
    this.rank = rank;
    this.suit = suit;
}

答案 1 :(得分:0)

你混淆了所有卡的可能等级和套装数组以及一张卡的具体套装和等级。我的建议是使用复数与单数来明确区分两者;并改变你的构造函数:

public class Card {
static String[] ranks = {"2","3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
    static String[] suits = {"Spades","Hearts", "Clubs", "Diamonds"};
    static Card[] deck = new Card[52];

    private String rank;
    private String suit;

    public Card(String rank, String suit)
    {
        this.rank = rank; // stores variable 'rank' in attribute 'rank'
        this.suit = suit; // same for 'suit'
    }

答案 2 :(得分:0)

您的构造函数正在使用String array而不仅仅是代表特定等级或颜色的String,而且在您尝试分配给静态数组的构造函数中。

我认为您不希望这样,将静态成员重命名为其他名称(例如static String ranks_available[] = {...}等),创建表示特定卡的等级和颜色的非静态成员:

String rank;
String color;

在构造函数中,将参数rank和color作为单独的字符串。

答案 3 :(得分:0)

您的Card构造函数期望使用两个字符串数组作为参数调用:String[] rank, String[] suit

进行循环时:

for(int x = 0; x<deck.length; x++)
{
    Card cards = new Card(rank[x%13], suit[x/13]);

}

rank[x%13]实际上是给你一个String。例如,x = 13然后rank[13%13] = rank[0] = "2"

"2"因为字符串rank数组的索引0等于该字符串:

static String[] ranks = {"2","3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};

鉴于构造函数期望数组为String,编译器会警告您String不是预期的参数类型。