공부/과제.

JAVA 문제풀이 09 숫자 야구 게임

햄이; 2021. 4. 26. 15:33

 

 

 

Q1. 숫자 야구 게임 (이 날 포트폴리오형 시험문제로 풀어냈던거라 주석이 과할정도로 많다ㅜ)

 

package Day8;

import java.util.Random;
import java.util.Scanner;

/*포트폴리오 시험용 숫자 야구게임*/
public class Portfolio1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Random r = new Random(); //랜덤값을 추출하는 함수
		Scanner sc = new Scanner(System.in);

		int[]com = new int[3]; //컴퓨터의 숫자가 저장될 배열 생성



		// int[] com에 1~9까지의 수를 랜덤으로 생성 저장
		for(int i=0; i<com.length; i++) {
			com[i] = r.nextInt(9)+1; 
		}


		// int[] com 배열의 중복값을 제거하고 중복되지 않을 때까지 랜덤값 재생성
		while(true){
			if(com[0] != com[1]){ //com[0]과 com[1]의 값이 서로 중복되지 않을 때
				if(com[0] != com[2] && com[1] != com[2]){// = 모든 값들이 중복되지 않을 때
					break;
				}else { // 만일 com[0]==com[2] || com[1]==com[2]일 경우 com[2]에 새 랜덤값 부여
					com[2] = r.nextInt(9)+1;
				}
			}else {//com[0]과 com[1]의 값이 중복일 때, com[1]에 새 랜덤 값 부여
				com[1] = r.nextInt(9)+1;
			}
		}


		//테스트에 용이하게 com[]의 값 전체 출력
		for(int i=0; i<com.length; i++) {
			System.out.print(com[i]+" ");
		}

		//야구게임 시작

		int total = 0; // 전체 게임 수 카운트

		while(true) {

			int [] user = new int[3]; // 유저에게 받을 숫자값을 저장할 배열 생성

			System.out.println("숫자 야구 게임입니다.");
			System.out.println("1~9 사이의 수를 중복되지 않게 입력해주세요.");


			//유저에게 받은 수가 1~9사이 내의 숫자인지 체크
			for(int i=0; i<user.length; i++) {
				user[i] =sc.nextInt();
				if(user[i]<1 || user[i]>9) { // 1 ~ 9사이의 숫자가 아닐 시
					System.out.println("범위 내 숫자가 아닙니다. 다시 입력해주세요");
					System.out.println();
					break;//게임 재시작
				}
			}
			
			if(user[0]>=1 && user[0]<=9 && user[1]>=1 && user[1]<=9 && user[2]>=1 && user[2]<=9) { 
				// user배열이 1~9사이 조건을 충족하는지 확인
				if(user[0]!=user[1] && user[0]!=user[2] && user[1]!=user[2]) {
					// user 배열들 간에 숫자가 중복되지 않는지 확인
					int ball = 0;
					int strike =0; 

					total++; // 게임 횟수 카운트


					for(int i=0; i<3; i++) { 
						for(int j=0; j<3; j++) {

							if(user[i] == com[j]) { //user 배열 속 값과 com 배열 속의 값이 같을 때
								if(i==j) {// ex) com[0] == com[0] 즉, 자릿수까지 값이 똑같을 때
									strike++; // 스트라이크 1추가
								}else { // 배열 속 값은 같지만 자릿수가 다를 때,
									ball++; // ball 1추가
								}
							}
						}
					}


					if(ball!=0 || strike !=0) { // ball이나 strike중 하나라도 값이 있을 시
						if(strike ==3) { // strike가 3개일 때 = 홈런, 프로그램 종료
							System.out.println("홈런입니다.");
							System.out.println("컴퓨터의 숫자는");
							for(int i=0; i<com.length; i++) {
								System.out.print(com[i]+" ");
							}
							System.out.println("총 게임 시도 횟수 : "+total+"회");
							System.out.println("프로그램을 종료합니다.");
							break;
						}else { // ball이나 strike의 값이 있지만 홈런은 아닐 때 이번 스코어 출력,게임 계속 진행
							System.out.println("이번 게임의 결과는 "+ball+"볼 "+strike+"스트라이크 입니다.");
							System.out.println();
						}
					}else if(ball==0 && strike ==0) { // ball도 strike도 값이 없을 때 아웃, 게임 계속 진행
						System.out.println("아웃입니다.");
						System.out.println();
					}

				}else { // 유저가 입력한 값 중 중복된 숫자가 있을 시 출력, 숫자 재입력
					System.out.println("중복된 숫자입니다. 다시 입력해주세요");
				}

			}


		}




	}

}

위 실행 결과

급하게 풀어냈더니

너무 지저분하게 나온 것 같다.

시간 날 때 수정해서 재 업로드 할 예정