Design a comparator for randomValue, generate a deck of cards, use this comparator to shuffle the cards, and then output the entire shuffled deck.

2. Design a comparator for the randomValue value of the existing poker class. After generating a deck of cards, use this comparator to shuffle the cards, and then output the entire shuffled deck.

Design a comparator for the rank value, and then sort and output the whole deck of cards to observe the effect.

import java.util.*;
public class Card implements Comparable<Card>{
    
    
	char suit;
	char rank;
	double randomValue;
	Card(char aSuit,char aRank)
	{
    
    
		suit=aSuit;
		rank=aRank;
		randomValue=Math.random();
	}
	void dispaly()
	{
    
    		System.out.print( Character.toString(suit)+Character.toString(rank)+' ');
	}
	public int compareTo(Card card)
	{
    
    
		 return this.randomValue>card.randomValue?1:(this.randomValue<card.randomValue?-1:0);
	}
	
}
class CompareRank implements Comparator<Card>
{
    
    
	public int compare(Card a,Card b)
	{
    
    
		return a.rank>b.rank?1:(a.rank<b.rank?-1:0);
	}
}
import java.util.*;
public class CardSort {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		char[] suits= {
    
    '梅','方','桃','心'};
		char[] values= {
    
    'A','2','3','4','5','6','7','8','9','T','J','Q','K'};
		List<Card> cards=new LinkedList<Card>();
		for(int i=0;i<13;i++)
		{
    
     for(int j=0;j<4;j++)
		  {
    
     cards.add(new Card(suits[j],values[i]));
		  }
		}
		cards.add(new Card('小','鬼'));
		cards.add(new Card('大','鬼'));
		Collections.sort(cards);
		for(int i=0;i<54;i++)
		{
    
    cards.get(i).dispaly();	
		}
		System.out.println();
		Collections.sort(cards,new CompareRank());
		for(int i=0;i<54;i++)
		{
    
    cards.get(i).dispaly();	
		}
	}
}

insert image description here

Guess you like

Origin blog.csdn.net/qq_45808700/article/details/118156602