숫자야구게임-Collection

이중호·2021년 11월 1일
0

고급자바

목록 보기
2/6

문제)Set을 이용하여 숫자 야구 게임 프로그램을 작성하시오.
(컴퓨터의 숫자는 난수를 이용하여 구한다)
(스트라이크는 S, 볼은 B로 나타낸다)


예시)컴퓨터의 난수 ==> 9 5 7

실행예시)
	숫자입력 => 3 5 6
	3 5 6 => 1S 0B
	숫자입력 => 7 8 9
	7 8 9 => 0S 2B
	숫자입력 => 9 7 5
	9 7 5 => 1S 2B
	숫자입력 => 9 5 7
	9 5 7 => 3S 0B
	
	축하합니다.
	당신은 4번만에 맞췄습니다.

public class BaseBallTest {

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);
		Set<Integer> computerSet = new HashSet<>();
		
		while(computerSet.size()<3){
			computerSet.add((int)(Math.random()*9)+1);
		}
		
		List<Integer> computerList = new ArrayList<>(computerSet);
		//System.out.println(computerList);
		int cnt = 0;
		while(true){
			cnt++;
			int strike = 0;
			int ball = 0;
			System.out.print("숫자입력 => ");
			String input = scan.nextLine();
			List<Integer> userList = new ArrayList<>();
			userList.add(Integer.parseInt(input.substring(0, 1)));
			userList.add(Integer.parseInt(input.substring(2, 3)));
			userList.add(Integer.parseInt(input.substring(4, 5)));
			System.out.print(input+" => ");
			for(int i=0; i<3; i++){
				if(computerList.get(i)==userList.get(i)){
					strike++;
					continue;
				}
				for(int j=0; j<3; j++){
					if(computerList.get(i)==userList.get(j)) ball++;
				}
			}
			System.out.println(strike+"S "+ball+"B");
			if(strike==3) {
				System.out.println("\n축하합니다.");
				System.out.println("당신은 "+cnt+"번만에 맞췄습니다.");
				break;
			}
		}
	}
}
profile
배워가는 신입개발자

0개의 댓글