공부기록/실습

12월 2일 - 예외사항 처리

project100 2023. 12. 2. 19:53
package Day1202;

import java.util.InputMismatchException;
import java.util.Scanner;

public class homework02 {
    public static void main(String[] args) {
        int ramdom = 20;
        int num = 0;
        int count = 0;

        Scanner sc = new Scanner(System.in);

        while (true){
            try {
                System.out.print("1~100의 숫자을 입력하세요 >> ");
                num = sc.nextInt();
                count++;


                if(num < ramdom){
                    System.out.println("UP!");
                } else if (num > ramdom){
                    System.out.println("Down!");
                } else {
                    System.out.println("정답!");
                    System.out.println("시도횟수 : " + count);
                    break;
                }
            } catch (InputMismatchException e) {
                System.out.println("숫자가 아닌 글자를 입력하셨습니다. 숫자를 다시 입력해 주세요.");
                // Consume the invalid input
                sc.next();
            }
        }
        sc.close();
    }
}