JAVA를 잡아라!...
JAVA_예외처리(Exception)_#1 본문
문제
사용자가 1~10 사이의 정수를 입력해야합니다. 단, 정상입력해야 종료!
정수입력 >> 정수
정수를 입력해주세요!
정수입력 >> 11
1~10 사이로 입력해주세요!
정수입력 >> 5
5를 입력했습니다! :D
[ 한글코딩 ]
while
사용자가 정수를 입력
if(정상입력이면)
break;
Code (예외처리 전)
package freefree;
import java.util.Scanner;
public class Freefree {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
int num = 0;
System.out.println("정수입력 >> ");
num = sc.nextInt();
if (num >= 1 && num <= 10) {
System.out.println(num + "를 입력했습니다! :D");
break;
}
System.out.println("1~10 사이로 입력해주세요!");
}
}
}
Console
try-catch
package practice01;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Exception02 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("정수입력 >> ");
int num;
try {
num = sc.nextInt();
} catch (InputMismatchException e) {
sc.nextLine(); // 버퍼 공간에 있는 잘못 입력된 값을 제거하는 역할
System.out.println("정수를 입력해주세요!");
continue;
}
if (1 <= num && num <= 10) {
System.out.println(num + "을(를) 입력했습니다! :D");
break;
}
System.out.println("1~10사이로 입력해주세요!");
}
}
}
try {} 가 에러가 난다면 catch로 들어가고 에러가 안난다면 catch무시하고 다음 소스코드 실행!
- Scanner클래스의 next(), nextLine() 메소드를 사용하여 입력 버퍼를 비울 수 있음
- 정수가 아닌 입력이 들어올 때 예외를 처리하고, 프로그램이 종료되지 않고 다시 입력을 받을 수 있도록 해줌
- next() : 공백을 기준으로 문자열을 읽기 때문에, 첫 번째 단어를 읽고 공백 이후의 문자열은 무시
- nextLine() : 사용자가 입력한 전체줄을 읽음
'JAVA > JAVA_복습문제' 카테고리의 다른 글
JAVA_MVC_#1_계산기 (0) | 2023.12.11 |
---|---|
JAVA_예외처리(Exception)_#2 (0) | 2023.12.08 |
JAVA_배열리스트_#1_Student (0) | 2023.12.07 |
JAVA_인터페이스_#1_TV (+ 싱글톤 패턴) (2) | 2023.12.07 |
JAVA_추상클래스_#2_Pokemon (2) | 2023.12.06 |