輸出牌的信息,並且打亂順序

public class Card {
	// 定義點數
	private int pointnum;
	// 定義花色
	private int Decor;

	public Card(int pointnum, int decor) {
		super();
		this.pointnum = pointnum;
		Decor = decor;
	}

	public int getPointnum() {
		return pointnum;
	}

	public void setPointnum(int pointnum) {
		this.pointnum = pointnum;
	}

	public int getDecor() {
		return Decor;
	}

	public void setDecor(int decor) {
		Decor = decor;
	}

	// 產生不重複的隨機數
	public static int[] randomNum(int n) {
		int[] a = new int[n];
		Random r = new Random();
		for (int i = 0; i < n;) {
			int d = 1 + r.nextInt(n);
			boolean flag = false;
			for (int x : a) {// 產生的隨機數和數組中的數據全部進行比較
				if (x == d) {// 如果存在就跳出
					flag = false;
					break;
				} else {// 否則一直比較下去
					flag = true;
				}
			}

			if (flag) {
				a[i++] = d;
			}

		}

		return a;
	}

	// 初始化
	public static void init(Card cs[]) {

		int m = 0;
		for (int i = 0; i < 13; i++) {
			for (int j = 0; j < 4; j++) {
				cs[m] = new Card(randomNum(13)[i], randomNum(4)[j]);
				m++;
			}
		}

	}

	// 輸出所有信息
	public static void show(Card[] cd) {
		for (int i = 0; i < 52; i++) {
			if (i % 5 == 0) {
				System.out.println();
			}
			if (cd[i].Decor == 1) {
				System.out.print("紅心" + cd[i].pointnum + " ");
			} else if (cd[i].Decor == 2) {
				System.out.print("梅花" + cd[i].pointnum + " ");
			} else if (cd[i].Decor == 3) {
				System.out.print("方塊" + cd[i].pointnum + " ");
			} else if (cd[i].Decor == 4) {
				System.out.print("紅桃" + cd[i].pointnum + " ");
			}

		}

	}

	// 隨機洗牌
	public static void shuffle(Card[] cd) {
		// 將對象數組轉換爲list集合
		List<Card> list = Arrays.asList(cd);
		// 打亂順序
		Collections.shuffle(list);
		// 轉換成對象數組
		Card[] cs = list.toArray(new Card[list.size()]);
		// 輸出

		System.out.println("洗牌後的結果:");
		show(cs);

	}

}

public class Main2 {
	public static void main(String[] args) {
		Card[] cd = new Card[52];
		// 初始化
		Card.init(cd);
		// 輸出所有信息
		Card.show(cd);
		System.out.println();
		// 隨機打亂
		Card.shuffle(cd);
	}
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章