/**
*本程序以斗地主为例,解释当字符串为数值时的大小比较(仅考虑3-10,不考虑其他数字或字母)
*
*在 String[] nums = ...一行,如不把3-9写为03-09,程序会认为"9" > "10",进而
*最终扑克牌的(升序)排序结果认为 10 最小,把 10 放在首位。
*
*原因:字符串对数值的比较仅限于同位数之间,3-9不会出问题,但是10是两位数,Java仅
*比较"10"和"9"的第一位,∵ 1 < 9, ∴ 10 < 9
*
*@author Prannt
*
*/
import java.util.ArrayList;
import java.util.Collections;
public class DouDiZhu {
public static void main(String[] args) {
//1.准备牌,定义一个存储54张牌的集合
ArrayList <String> poker = new ArrayList<>();
//定义两个数组,一个数组存储牌的花色,另一个数组存储牌的序号
String [] colors = {"♠","♥","♣","♦"};
String [] nums = {"03","04","05","06","07","08","09","10","J","Q","K","A","2"};
//先把大王和小王存储到poker集合中
poker.add("大王");
poker.add("小王");
//循环嵌套遍历两个数组,组装52张牌
for(String num : nums){
for (String color : colors) { //快捷键:colors.for
//System.out.print((num + color) + " ");
//把组装好的牌存储到poker集合中
poker.add(num + color);
}
}
//System.out.println(poker);
//2.洗牌
Collections.shuffle(poker);
//System.out.println(poker);
//3.发牌。定义四个集合,存储玩家的牌和底牌
ArrayList <String> player01 = new ArrayList<>();
ArrayList <String> player02 = new ArrayList<>();
ArrayList <String> player03 = new ArrayList<>();
ArrayList <String> diPai = new ArrayList<>();
//遍历poker集合,获取每一张牌
for (int i = 0; i < poker.size(); i++) {
String s = poker.get(i);
if(i >= 51) {
//给底牌发牌
diPai.add(s);
Collections.sort(diPai); //给发的牌排序
} else if(i % 3 == 0) {
player01.add(s);
Collections.sort(player01);
} else if(i % 3 == 1) {
player02.add(s);
Collections.sort(player02);
} else if(i % 3 == 2) {
player03.add(s);
Collections.sort(player03);
}
}
System.out.println(player01);
System.out.println(player02);
System.out.println(player03);
System.out.println(diPai);
}
}
/*不把 3-9 写为 03-09,最终的升序结果为(未考虑3-10以外的其他数字和字母):
[10♥, 2♣, 2♦, 3♠, 5♥, 6♣, 6♦, 7♣, 7♦, 8♥, 9♥, 9♦, A♠, A♣, J♥, K♠, Q♦]
[10♠, 2♥, 3♣, 3♥, 4♥, 5♠, 6♥, 7♥, 8♠, 8♦, 9♠, J♠, J♣, J♦, K♣, Q♠, Q♣]
[10♣, 10♦, 2♠, 3♦, 4♠, 4♣, 4♦, 5♣, 6♠, 7♠, 8♣, 9♣, A♥, A♦, Q♥, 大王, 小王]
[5♦, K♥, K♦]
*/
/*把 3-9 写为 03-09,最终的升序结果为(未考虑3-10以外的其他数字和字母):
[03♣, 03♥, 03♦, 04♣, 05♣, 06♣, 06♥, 06♦, 07♠, 08♣, 08♦, 2♣, 2♦, A♠, A♦, J♥, Q♥]
[03♠, 04♠, 04♥, 05♠, 05♦, 07♦, 08♠, 08♥, 09♠, 09♣, 09♦, 10♠, A♥, Q♠, Q♦, 大王, 小王]
[04♦, 05♥, 06♠, 07♣, 07♥, 09♥, 10♣, 10♥, 2♠, 2♥, A♣, J♣, J♦, K♠, K♣, K♥, K♦]
[10♦, J♠, Q♣]
*/
字符串是数值的大小比较
最新推荐文章于 2024-10-26 22:51:39 发布