728x90
반응형
package chap7;
class SutdaCard {
int number;
boolean isKwang;
SutdaCard() { this(1,true); }
SutdaCard(int number, boolean isKwang) {
this.number = number;
this.isKwang = isKwang;
}
public String toString () {
return number + (isKwang?"k":"");
}
}
/*
* SutdaCard 20장으로 이루어진 SutdaDeck 클래스 구현하기
* 1. 멤버 변수
* SutdaCard 20장을 가지고 있다.
* SutdaCard는 같은 수의 카드를 2장씩 총 20장으로 이루어져 있다.
* 그중 1,3,8번호의 카드는 두장 중 한장이 광인 카드다.
* 2. 생성자
* SutdaCard 20장을 생성하여 멤버 변수인 배열에 저장하기
* 3. 메서드
* a. void shuffle()
* 기능 : 카드의 위치를 뒤섞는다.
* b. SutdaCard pick(int index)
* 기능 : index에 해당하는 카드 한장을 반환한다.
* c. SutdaCard pick()
* 기능 : 임의의 카드 한장을 반환한다.
*/
class SutdaDeck{
SutdaCard[] cards = new SutdaCard[20];
SutdaDeck() { //생성자
for(int i=0; i<cards.length; i++) {
cards[i] = new SutdaCard
((i%10+1), ((i==0||i==2||i==7)?true:false));
}
}
//카드섞기
void shuffle() {
for(int i=0; i<1000; i++) {
int f = (int)(Math.random() * 20); // 0 ~ 19 임의의 값
int t = (int)(Math.random() * 20); // 0 ~ 19 임의의 값
SutdaCard s = cards[f];
cards[f] = cards[t];
cards[t] = s;
}
}
SutdaCard pick(int index) {
return cards[index];
}
SutdaCard pick() {
return cards[(int)(Math.random() * 20)];
}
public String toString() {
String s ="";
for(SutdaCard c : cards) {
s += c + ",";
}
return s;
}
}
public class Exam1 {
public static void main(String[] args) {
SutdaDeck deck = new SutdaDeck();
//1K,2,3K,4,5,6,7,8K,9,10,1,2,3,4,5,6,7,8,9,10
System.out.println(deck);
deck.shuffle(); //카드섞기
System.out.println(deck);
System.out.println(deck.pick(0));
System.out.println(deck.pick(1));
System.out.println(deck.pick());
}
}
728x90
반응형
'study > Java' 카테고리의 다른 글
[Java] 22. Test1 (모든 클래스에 getPay() 메서드를 구현하기 (0) | 2022.03.21 |
---|---|
[Java] 22. 다형성 예제 (0) | 2022.03.21 |
[Java] 22. super 생성자 (0) | 2022.03.21 |
[Java] 22. super 예약어 (0) | 2022.03.21 |
[Java] 22. 오버로딩, 오버라이딩 예제 (0) | 2022.03.21 |