[Exception-1] NullPointerException, NumberFormatException

seratpfk·2022년 8월 4일
0

JAVA

목록 보기
79/96

NullPointerException : null값이 어떤 메소드를 호출할 때 발생

	public static void m1() {
		String[] hobbies = new String[5];
		hobbies[1] = "수영";  
		hobbies[2] = "골프";
		hobbies[3] = "영화";
		hobbies[4] = "집콕";
		for(int i = 0; i < hobbies.length; i++) {
			if(hobbies[i].equals("수영")) { 
				System.out.println("취미가 나와 같군요");
			}
		}
	}
  • hobbies[0]의 값이 null이기 때문에 오류 발생

NullPointerException 회피

	public static void m2() {  
		String[] hobbies = new String[5];
		hobbies[1] = "수영";  
		hobbies[2] = "골프";
		hobbies[3] = "영화";
		hobbies[4] = "집콕";
		for(int i = 0; i < hobbies.length; i++) {
			if(hobbies[i] != null && hobbies[i].equals("수영")) { 
				//if(hobbies[i].equals("수영") && hobbies[i] != null) - 오류
				// 순서 바꾸면 오류가 난다.
				System.out.println("취미가 나와 같군요");
			}
		}
	}

출력:
취미가 나와 같군요

NumberFormatException : String을 Number타입으로 변경할 때 발생

	public static void m3() {
		Scanner sc = new Scanner(System.in);
		System.out.println("이름 입력(필수) >>> ");
		String name = sc.nextLine(); 
		System.out.println("나이 입력(선택) >>> ");
		String strAge = sc.nextLine();  
		int age = Integer.parseInt(strAge); 
		System.out.println("이름:" + name + ", 나이:" + age + "살");
	}
  • 입력 없이 Enter만 누르면 strAge는 빈 문자열을 가지므로 오류 발생

NumberFormatException 회피

	public static void m4() {
		Scanner sc = new Scanner(System.in);
		System.out.println("이름 입력(필수) >>> ");
		String name = sc.nextLine(); 
		System.out.println("나이 입력(선택) >>> ");
		String strAge = sc.nextLine();
		int age;
		if(strAge.isEmpty()) {
			age = 0;  
		} else {
			age = Integer.parseInt(strAge);
		}
		System.out.println("이름:" + name + ", 나이:" + age + "살");
	}
  • strAge 입력 안했을 시 age를 0으로 출력한다.

0개의 댓글