티스토리 뷰

import java.util.Random;

class Player {
    int num; //레인번호
    String country; // 국가
    int m; // 전진거리

    Player(int num, String country) { // 생성자 => 레인번호, 국가
        this.num = num;
        this.country = country;

    }

    void runAndCheck(int num, Random r) { // 이동거리(전진) 실행 메서드 // 밖에서 레인번호만 알려주면 된다.
        if (num != this.num) { //돌발 레인번호와 내 레인번호가 일치하지 않으면ㅇ
            m += r.nextInt(10) + 1; // 전진(전진거리에 이동거리만큼을 누적)
        }
        System.out.println(country + "선수 이동거리는 " + m + "M 입니다.");
    }
}


class Game {
    String[] c = {"한국", "중국", "미국", "러시아"};
    Player[] p = new Player[4]; // 배열 각각의 객체를 생성

    public Game() {
        for (int i = 0; i < this.p.length; i++) {
            this.p[i] = new Player(i + 1, c[i]);
        }
    }
}

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Random r = new Random();
        Game game = new Game();

        Player[] p = game.p;

        while (p[0].m < 100 && p[1].m < 100 && p[2].m < 100 && p[3].m < 100) {
            int dol = r.nextInt(4) + 1;
            for (int i = 0; i < p.length; i++) {
                p[i].runAndCheck(dol, r);
            }
        }

        int max = -1;
        for (int i = 0; i < p.length; i++) { // 우승국 추출하기(최댓값 활용)
            if (max < p[i].m) {
                max = p[i].m;
            }
        }

        for (int i = 0; i < p.length; i++) { // 우승국 출력하기
            if (p[i].m == max) {
                System.out.println(p[i].country + "우승국입니다.");
                break;
            }
        }
    }

}
728x90
반응형
Comments
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
250x250