1. 程式人生 > >使用LinkedList存儲一副撲克牌,然後實現洗牌功能。

使用LinkedList存儲一副撲克牌,然後實現洗牌功能。

pub creat link his println 數組 tostring tint poke

/*
需求: 使用LinkedList存儲一副撲克牌,然後實現洗牌功能。



*/
//撲克類
class Poker{
    String  color; //花色
    String num;    //點數
    public Poker(String color, String num) {
        super();
        this.color = color;
        this.num = num;
    }
    @Override
    public String toString() {
        return "{"+color+num+"}";
    }
}
public class Demo2 { public static void main(String[] args) { LinkedList pokers = createPoker(); shufflePoker(pokers); showPoker(pokers); } //洗牌的功能 public static void shufflePoker(LinkedList pokers){ //創建隨機數對象 Random random = new Random();
for(int i = 0 ; i <100; i++){ //隨機產生兩個索引值 int index1 = random.nextInt(pokers.size()); int index2 = random.nextInt(pokers.size()); //根據索引值取出兩張牌,然後交換兩張牌的順序 Poker poker1 = (Poker) pokers.get(index1); Poker poker2 = (Poker) pokers.get(index2); pokers.set(index1, poker2); pokers.set(index2, poker1); } }
//顯示撲克牌 public static void showPoker(LinkedList pokers){ for(int i = 0 ; i<pokers.size() ; i++){ System.out.print(pokers.get(i)); //換行 if(i%10==9){ System.out.println(); } } } //生成撲克牌的方法 public static LinkedList createPoker(){ //該集合用於存儲撲克對象。 LinkedList list = new LinkedList(); //定義數組存儲所有的花色與點數 String[] colors = {"黑桃","紅桃","梅花","方塊"}; String[] nums = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"}; for(int i = 0 ; i < nums.length ; i++){ for(int j = 0 ; j<colors.length ; j++){ list.add(new Poker(colors[j], nums[i])); } } return list; } }

/*需求: 使用LinkedList存儲一副撲克牌,然後實現洗牌功能。


*///撲克類class Poker{String color; //花色String num;//點數public Poker(String color, String num) {super();this.color = color;this.num = num;}@Overridepublic String toString() {return "{"+color+num+"}";}}public class Demo2 {public static void main(String[] args) {LinkedList pokers = createPoker();shufflePoker(pokers);showPoker(pokers);}//洗牌的功能public static void shufflePoker(LinkedList pokers){//創建隨機數對象Random random = new Random();for(int i = 0 ; i <100; i++){ //隨機產生兩個索引值int index1 = random.nextInt(pokers.size());int index2 = random.nextInt(pokers.size());//根據索引值取出兩張牌,然後交換兩張牌的順序Poker poker1 = (Poker) pokers.get(index1);Poker poker2 = (Poker) pokers.get(index2);pokers.set(index1, poker2);pokers.set(index2, poker1);}}//顯示撲克牌public static void showPoker(LinkedList pokers){for(int i = 0 ; i<pokers.size() ; i++){System.out.print(pokers.get(i));//換行if(i%10==9){System.out.println();}}}//生成撲克牌的方法public static LinkedList createPoker(){//該集合用於存儲撲克對象。LinkedList list = new LinkedList();//定義數組存儲所有的花色與點數String[] colors = {"黑桃","紅桃","梅花","方塊"};String[] nums = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};for(int i = 0 ; i < nums.length ; i++){for(int j = 0 ; j<colors.length ; j++){list.add(new Poker(colors[j], nums[i]));}}return list;}}

使用LinkedList存儲一副撲克牌,然後實現洗牌功能。