扑克游戏和比较器的问题?

时间:2015-05-06 00:30:05

标签: java comparator poker

我正在尝试创建一个扑克游戏,我在其中创建了Card类中的牌组,并使用比较器按字母顺序对牌组进行排序。我在比较器和我的经销商类中遇到了什么问题,(这是我创建牌组,随机播放以及调用比较器的地方)。当我的CompareCards编译时,我的经销商类会给我错误:

    Dealer.java:24: error: incompatible types: void cannot be converted to String
    String s = Collections.sort(deck);
                               ^
 Note: Dealer.java uses unchecked or unsafe operations.
 Note: Recompile with -Xlint:unchecked for details.

我知道在进行排序时,您必须包含比较器名称,但在这种情况下,它不会以任何方式工作。这是我的卡片类:

import java.util.*;
public class Card{
    String suit = null;
    String value = null;
    String rank = null;

    public static final String[] SUIT = {"C", "D", "H", "S" };

    public static final String[] RANK = {"A","2","3","4","5","6","7","8","9","T","J","Q","K"};

    public Card(int i, int j){
        suit = RANK [i];
        rank = SUIT [j];
        value = rank + suit;
    }
    public String getSuit(){
        return suit;
    }

    public String getRank(){
        return rank;
    }

    public String toString(){
        return(value);
    }
}

这是我的Comparator和CompareCards类:

public interface Comparator <Card>{
    public int compare(Card o1, Card o2);
}

public class CompareCards implements Comparator<Card>{
    public int compare(Card c1, Card c2){
        int x = 0;
        int y = 0;
        int dx = c1.getRank() - c2.getRank();
        if(dx == 0){
            x = c1.getRank()-c2.getRank();
        }
        else{
            y = c1.getSuit() - c2.getSuit();
        }
        return x;
    }

以下是经销商类:

import java.util.*;
public class Dealer{

public static void main(String[]args){
    // creating deck
    List<Card> deck= new ArrayList<Card>();

    // calling Card
    for(int i = 0; i < 13  ; i++){
        for(int j = 0; j < 4 ; j++){
            // String s = RANK[i] +SUIT[j];
            deck.add(new Card(i, j));
        }
    }
    finding21(deck);
}

public static void finding21 (List deck){

    String s = Collections.sort(deck);
    System.out.println("Sorted deck: " + s);
    // After I sort the deck I am supposed to do a binary search
    // for the queen of hearts
     /* Collections.shuffle(deck);
          System.out.println("Shuffled deck: " + deck);
          String HQ =  Collections.binarySearch(deck, "HQ");
          System.out.print(HQ);

          System.out.println(queenH);*/
    }
}    

1 个答案:

答案 0 :(得分:4)

Collections.sort执行就地排序,但不返回值。

这就是为什么编译器说你无法将void转换为String

void类型用于没有返回值的函数。

只需使用:

Collections.sort(deck);

如果您想在之后打印已排序的deck,可以使用:

System.out.println("Sorted deck: " + deck);