본문 바로가기
알고리즘 문제연습/기초 알고리즘

[001] Baseball게임 (중복 X, 10번의 기회)

by 은z 2021. 5. 12.

문제

- 야구게임을 구현하시오.

- 단, 랜덤숫자는 중복되지 않아야 하고 사용자는 10번의 기회가 주어집니다.

- 배열, for, while문 이용

 

소스코드

```java
import java.util.Scanner;

public class BaseballGame {

	public static void main(String[] args) {
		//초기화
		int com[] = new int[3];
		int user[] = new int[3];
		Scanner sc = new Scanner(System.in);
		
		boolean replay = true;
		//컴퓨터 랜덤값 (단, 중복되지 않도록)
		while(replay) {
			boolean flag = false;
			int chance = 0;
			while(true) {
				for(int i=0; i<com.length; i++) {
					com[i] = (int) (Math.random()*10) + 1; //1~10까지
					}
				if(com[0] != com[1] && com[0] != com[2] && com[1] != com[2]) {
					break;
				}	
			}
			for(int i=0; i<com.length; i++) {
				System.out.println("컴퓨터의 " + (i+1) + "번째 값 > " + com[i]);
				}
			
			//유저 값 입력(단, 중복되지 않도록 - 기회 10번)
			while(chance < 10) {
				System.out.println("-----------------");
				System.out.println("숫자를 입력하세요");
				while(true) {
					for(int i=0; i<user.length; i++) {
						System.out.print("유저의 " + (i+1) + "번째 값 > ");
						user[i] = sc.nextInt();
						}
					if(user[0] != user[1] && user[0] != user[2] && user[1] != user[2]) {
						break;
					}else {
						System.out.println("중복되는 숫자! 다시 입력하세요");
					}
				}
				//컴퓨터 값과 유저 값 비교
				int strike = 0;
				int ball = 0;
				
				for(int i=0; i<com.length; i++) { //0,1,2
					for(int j=0; j<user.length; j++) { //0,1,2
						if(com[i] == user[j] && i == j) {
							strike++;
						}else if(com[i] == user[j]) {
							ball++;
						}
					}
				}
				System.out.println(strike + "스트라이크 " + ball + "볼");
				chance++;
				System.out.println("잔여 기회 > " + (10-chance) );
				//메시지
				if(strike == 3) {
					flag = true;
					break;
				}			
			}
			if(flag == true) {
				System.out.println("게임 승리! 다시 재도전? y/n");
			}else {
				System.out.println("게임 오버~ 다시 재도전? y/n");
			}
			String key = sc.next();
			if(key.equals("y")) {			
				replay = true;
			}else if(key.equals("n")) {
				replay = false;
			}
		}
		System.out.println("게임을 완전히 끝냅니다.");	
	}
}
```

댓글