-
[JAVA] Exception in thread "main" java.util.InputMismatchExceptionerror 2023. 4. 20. 09:25
에러 : Exception in thread "main" java.util.InputMismatchException
scanner로 입력받을 때 자료형이 달라서 생기는 오류
(정수로 입력 받기로 했으나 정수가 아닌 다른 형태가 올 때)
> try-catch 구문으로 제대로 된 값을 받을 때까지 입력받기
> 전체를 while문으로 받고 try-catch를 통해 예외가 발생했을 경우 사용자에게 다시 물어본다
> 사용자 Y 입력 받는 경우 while문에 의해서 다시 처음부터 숫자 입력받도록 코드 생성
while (startOrStop.toUpperCase().equals("Y")) { System.out.println("\n1 또는 2를 입력해 주세요."); System.out.println("(1: 파일 대화, 2: 사용자 입력 대화)"); try { int inputnum = sc.nextInt(); switch(inputnum) { case 1: // 파일 대화 이용 ca.callOpenAi(client, newFilePath, 1, bf); break; case 2: // 사용자 대화 이용 ca.callOpenAi(client, newFilePath, 2, bf); break; default : System.out.println("\n 1 또는 2를 입력해 주세요."); } } catch (InputMismatchException e) { System.out.println("\n정수가 아닙니다. 1 또는 2를 입력해 주세요."); } System.out.println("api_test 계속 진행하려면 Y를 입력해 주세요."); sc.nextLine(); String input = sc.nextLine(); if (!input.toUpperCase().equals("Y")) { startOrStop = "N"; sc.close(); } }
728x90'error' 카테고리의 다른 글