[ 작업 환경 ]
Windows10
jdk-15
1. Coin 객체 생성
// Coin.java
public class Coin {
private final int HEADS = 1;
private int face;
public Coin() {
flip();
}
public void flip() {
face = (int)(Math.random() * 2);
}
public boolean isHeads() {
return (face == HEADS);
}
public String toString() {
return (face==HEADS) ? "Heads" : "Tails";
}
}
2. 동전 뒤집기
// CountFlips.java
public class CountFlips {
public static void main (String[] args) {
final int FLIPS = 1000;
int heads = 0, tails = 0;
Coin myCoin = new Coin();
for (int count = 1; count <= FLIPS; count++) {
myCoin.flip();
if (myCoin.isHeads()) {
heads ++;
}
else {
tails ++;
}
}
System.out.println("Number of flips : " + FLIPS);
System.out.println("Number of heads : " + heads);
System.out.println("Number of tails : " + tails);
}
}
3. 컴파일 및 실행
javac Coin.java
javac CountFlips.java
java CountFlips