본문 바로가기
1. Java 자바/1_0. 책, 강의

[명품 자바 프로그래밍] 3장 159쪽 오픈 챌린지_정답

by 비소야 2022. 10. 10.
728x90

명품 자바 프로그래밍 3장 159쪽 오픈 챌린지_정답

luxury java programming ch3 p159 openchallenge answer
 

답: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.util.Scanner;
 
public class RandomNumberGame {
    public static void main(String[] args) {                    
        Scanner scanner = new Scanner(System.in);               
 
        // 선언
        int randomNumber, answer, count, start, end;
        String restart;
        // 로직
        while (true) {
            // 0. 변수 초기화
            count = 1; start = 0; end = 99;
            // 1. 0 ~ 99 랜덤 수 결정
            randomNumber = (int) (Math.random() * 100);
            System.out.println("수를 결정하였습니다. 맞추어 보세요");
            while (true) {
                // 2. 사용자 입력
                System.out.println(start + "-" + end);
                System.out.print(count++ + ">>");
                answer = scanner.nextInt();
                // 3. 결과 판별
                if (answer == randomNumber) {
                    System.out.println("맞았습니다.");
                    break;
                } else if (answer < randomNumber) {
                    System.out.println("더 높게");
                    start = answer;
                    continue;
                } else if (answer > randomNumber) {
                    System.out.println("더 낮게");
                    end = answer;
                    continue;
                }
            }
            // 4. 게임 재시작 여부 판별
            System.out.println("다시하시겠습니까(y/n)>>");
            restart = scanner.next();
            if (restart.charAt(0== 'n') {
                break;
            } else {
                continue;
            }
        }
 
        scanner.close();
    }
}
cs

 

// 맨 처음부터 로직을 확실하게 짜는 것이 좋다. 그러나, 감이 잘 잡히지 않는다면 코드를 먼저 짜고 로직을 수정하는 방법이 아니라 종이에 대략적으로 글을 적어보면서 로직을 짜는 것이 좋다.

728x90