올바른 숫자 입력시 까지 반복

MSKim·2023년 2월 27일
0

Java

목록 보기
6/19
public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);	// 입력받는 함수 Scanner
        int a = 0;
        while(true){
            System.out.printf("숫자 : ");
            try{
                a = sc.nextInt(); // 대기, 숫자 하나 입력될 때 까지(예외발생 시 catch로 바로넘어감)
                sc.nextLine();  // 버퍼를 비운다
                break;
            }catch(Exception e){
                sc.nextLine();  // 버퍼를 비운다
                System.out.println("숫자를 입력해 주세요.");
            }
        }
        System.out.printf("입력된 숫자 : %d\n", a);
        sc.close();
    }
}
profile
Today I Learned

0개의 댓글