: 내장 객체인 Collections 객체의 셔플(Shuffle) 사용하여
컬렉션에서 배열(list) 안에 있는 데이터를 랜덤으로 섞어주는 기능
package basic;
public class Card { // 카드 저장 클래스
String suit;
String number;
public Card(String suit, String number) { // 생성자
this.suit = suit;
this.number = number;
}
@Override
public String toString() {
return "(" + suit + " " + number + ")";
}
}
package basic;
import java.util.ArrayList;
public class Player { // 플레이어 클래스
ArrayList<Card> card = new ArrayList<Card>();
// Card 타입의 ArrayList 객체 생성
public void getCard(Card card) {
this.card.add(card);
}
public void showCards() {
System.out.println(card);
}
}
package basic;
import java.util.ArrayList;
import java.util.Collections;
public class Random {
ArrayList<Card> random = new ArrayList<Card>();
String[] suit = {"CLUB", "DIAMOND", "HEART", "SPACE"};
String[] number = {"2", "3", "4", "5", "6", "7", "8", "9", "2", "10", "J", "Q", "K", "A"};
public Random() {
for (int i = 0; i < suit.length; i++) { // 카드 모양
for (int j = 0; j < number.length; j++) { // 카드 숫자
random.add(new Card(suit[i], number[j]));
}
}
}
public void suffle() {
Collections.shuffle(random);
// ArrayList<Card>에 있는 값들이 랜덤으로 출력
}
public Card deal() {
return random.remove(0);
// remove(): 해당 인덱스를 삭제, 반환
// Card 객체에서 첫 번째 요소를 삭제 후 반환
}
}
package basic;
public class Game {
public static void main(String[] args) {
Random rnd = new Random();
rnd.suffle();
// Random의 suffle() 실행: 랜덤 출력
Player p1 = new Player(); // 플레이어 객체 생성
Player p2 = new Player();
p1.getCard(rnd.deal());
p2.getCard(rnd.deal());
// Random의 deal() 실행: 첫 번째 카드 가져옴 -> Player의 getCard() 실행: 가져온 카드 저장
p1.showCards();
p2.showCards();
// Player의 showCards() 실행: ArrayList<Card>에 저장된 카드를 출력
}
}