프로그래밍 언어 복습/JAVA
#29 JAVA 주사위 클래스 게임
사재원 교수
2022. 5. 23. 15:54
빨간주사위와 파란주사위가 있습니다.
각자 다른 객체로써 주사위가 존재하며 메소드를 이용해 주사위를 굴립니다. 1~6랜덤의 숫자가
누적되어 각각 쌓이며 50을 먼저 넘기는 주사위가 승리합니다.
단 50을 함께 넘어갔다면 더 큰 숫자의 주사위가 승리하게 됩니다.
정답공개 !
package hihihi;
import java.util.Random;
class Dice{
Random r = new Random();
int result;
String name;
Dice(String name){
this.name = name;
}
public void Play() {
this.result += r.nextInt(6)+1; //0~9까지 랜덤 수
}
}
public class protect {
public static void main(String[] args) {
Dice red = new Dice("빨간 다이스");
Dice blue = new Dice("파란 다이스");
while(true) {
red.Play();
blue.Play();
if(red.result>50 || blue.result>50) {
break;
}
}
System.out.println("빨간 주사위 : " + red.result);
System.out.println("파란 주사위 : " + blue.result);
if(red.result < blue.result) {
System.out.println("파란 주사위가 이겼습니다 ! ");
}else {
System.out.println("빨간 주사위가 이겼습니다 ! ");
}
}
}
감사합니다.