类型不匹配无法从String转换为String []

时间:2015-08-15 18:20:38

标签: java

当我跑步时:

import java.util.Scanner;

public class War {

    public static void main(String[] args) {
        String[] deckcards=deck();
        String[] player1cards=player1Cards(deckcards);
    }
    public static String[] deck(){
        String[] Cards = {"spades1","spades2","spades3", "spades4", "spades5", "spades6", "spades7", "spades8", "spades9", "spades10", "spadesJ", "spadesQ", "spadesK", "spadesA", "clubs1", "clubs2", "clubs3", "clubs4", "clubs5", "clubs6", "clubs7", "clubs8", "clubs9", "clubs10", "clubsJ", "clubsQ", "clubsK", "clubsA", };
        return Cards;
    }
    public static String [] player1Cards(String[] deckcards){
        String[] player1cards = deckcards[0];
        return player1cards;
    }

我收到两个错误。

一个错误告诉我

Type mismatch cannot convert from String to String[]

另一个错误告诉我出现了一个行断点错误:

String[] player1cards = deckcards[0];

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

你的问题在这里:

String[] player1cards = deckcards[0];

deckcards[0]String类型数组的元素。所以它是一个String变量。但是你试图将它分配给String[] player1cards,这是一个Java中不允许的字符串数组。

答案 1 :(得分:0)

String[]的元素是String,而不是String[],但是说这不能解决您的问题。

除了设计和风格的问题,我认为你的意图是:

public class War {

    public static void main(String[] args) {
        String[] deckcards=deck();
        // shuffle deck
        List<String> list = new ArrayList<>(Arrays.asList(deckcards));
        Collections.shuffle(list);
        deckcards = list.toArray(new String[]{});
        // deal from deck
        String[] player1cards=player1Cards(deckcards, 0, 5);
    }
    public static String[] deck(){
        String[] Cards = {"spades1","spades2","spades3", "spades4", "spades5", "spades6", "spades7", "spades8", "spades9", "spades10", "spadesJ", "spadesQ", "spadesK", "spadesA", "clubs1", "clubs2", "clubs3", "clubs4", "clubs5", "clubs6", "clubs7", "clubs8", "clubs9", "clubs10", "clubsJ", "clubsQ", "clubsK", "clubsA", };
        return Cards;
    }
    public static String [] player1Cards(String[] deckcards, int from, int quantity){
        String[] player1cards = Arrays.copyOfRange(deckcards, from, from + quantity);
        return player1cards;
    }
}

免责声明:未经测试的代码(在iPhone上翻阅)并没有采取任何措施来解决设计问题,但是你会有一些有用的东西。