內部類 使用方法 (撲克 和 卡片)
阿新 • • 發佈:2018-12-15
mcc/Test.java
package mcc; //撲克類(一副撲克) class Poker { //內部類Card public class Card { private String suite; // 花色 private int face; // 點數 public Card(String suite, int face) { this.suite = suite; this.face = face; } @Override public String toString() { String faceStr = ""; switch (face) { case 1: faceStr = "A"; break; case 11: faceStr = "J"; break; case 12: faceStr = "Q"; break; case 13: faceStr = "K"; break; default: faceStr = String.valueOf(face); } return suite + faceStr; } } //Poker類 成員 private static String[] suites = { "黑桃", "紅桃", "梅花", "方塊" }; private static int[] faces = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; private Card[] cards; //構造器 public Poker() { //構造52個Card物件 存放在cards 陣列中 cards = new Card[52]; for (int i = 0; i < suites.length; i++) { for (int j = 0; j < faces.length; j++) { cards[i * 13 + j] = new Card(suites[i], faces[j]); } } } //洗牌 (隨機亂序) public void shuffle() { int len = cards.length; for (int i = 0; i < len; i++) { int index = (int) (Math.random() * len); Card temp = cards[index]; cards[index] = cards[i]; cards[i] = temp; } } //獲取一個Card 物件 public Card getCard(int index) { return cards[index]; } } public class Test { public static void main(String[] args) { Poker poker = new Poker(); poker.shuffle(); // 洗牌 Poker.Card c1 = poker.getCard(0); // 發第一張牌 // 對於非靜態內部類Card // 只有通過其外部類Poker物件才能建立Card物件 Poker.Card c2 = poker.new Card("紅心", 1); // 自己建立一張牌 System.out.println(c1); // 洗牌後的第一張 System.out.println(c2); // 列印: 紅心A } }