问题描述
问题描述
扑克牌排序:构造扑克牌数组,对扑克牌进行排序。排序原则如下:数字从小到大是2-10、J、Q、K和A,花色从小到大是方块(diamond)、梅花(club)、红桃(heart)、黑桃(spade)。两张牌比较时先看数字,数字相同时看花色。要求对输入的扑克牌进行从小到大排序。
输入五张牌(表示黑桃2、红桃3、黑桃3、方块A和梅花J):2s3h3sAdJc
输出结果应为:2 s 3 h 3 s J c A d数组长度固定为5。
参考代码
package 扑克排序;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sr = new Scanner(System.in);
//扑克牌的号数
String[] id = {"0","0","2","3","4","5","6","7","8","9","10","J","Q","K","A"};
card[] arr = new card[5];//规定有五张牌
for (int i = 0; i < arr.length; i++) {
int num = num(sr.next());
String color = sr.next();
int level = 0;
//根据牌的花色确定优先级
switch (color.charAt(0)) {
case 'd':
level = 1;
break;
case 'c':
level = 2;
break;
case 'h':
level = 3;
break;
case 's':
level = 4;
break;
}
//创建牌
arr[i] =new card(num,color,level);
}
Arrays.sort(arr ,new Comparator<card>() {
//创建比较器
public int compare(card o1, card o2) {
//首先比较牌号
if(o1.num!=o2.num)
return o1.num-o2.num;
else//一样的话比较牌的等级
return o1.level-o2.level;
}
});
for (int i = 0; i < arr.length; i++) {
System.out.print(id[arr[i].num]+" "+arr[i].color+" ");
}
}
private static int num(String next) {
//如果是JQKA返回他的等级
if(next.equals("J") )return 11;
if(next.equals("Q") )return 12;
if(next.equals("K") )return 13;
if(next.equals("A") )return 14;
//否则直接返回数字
return Integer.parseInt(next);
}
}
//扑克牌类
class card{
int num;//牌号
String color;//颜色
int level;//根据颜色确定等级
public card(int num , String color ,int level){
this.num = num;
this.color = color;
this.level = level;
}
}