[24.09.20] TIL

yy·2024년 9월 20일

개발일지

목록 보기
107/122

JAVA공부중

예외발생: Exception in thread "main" java.util.InputMismatchException

문제

scanner를 이용 사용자의 값을 받아 배열처리를 하고있는 와중에 발생한 예외이다. 사용자에게 받는 값이 설정된 자료형과 맞지않아 생긴 예외이다.
상품의 이름과 상품의 가격을 연달아 받아야하는데 아무래도 그 코드가 꼬인 듯하다.

문제의 코드 (상품등록 시 예외가 발생함)

package array;

import java.util.Scanner;

public class ArrayEx9 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int maxProducts = 10;
        String[] productNames = new String[maxProducts];
        int[] productPrices = new int[maxProducts];
        int productCount = 0;


        while (true) {
            System.out.println("1. 상품등록 | 2. 상품목록 | 3.종료\n메뉴를 선택하세요:");
            int options = scanner.nextInt();

            //상품등록
            if (options == 1) {
                if (productCount >= maxProducts) {
                    System.out.println("더 이상 상품을 등록할 수 없습니다.");
                    continue;
                }
                System.out.println("상품 이름을 입력하세요: ");
                productNames[productCount] = scanner.nextLine();
                scanner.nextInt();
                System.out.println("상품 가격을 입력하세요: ");
                productPrices[productCount] = scanner.nextInt();

                productCount++;

                //상품목록
            } else if (options == 2) {
                if(productCount == 0) {
                    System.out.println("등록된 상품이 없습니다.");
                    continue;
                }

                for (int i = 0; i <productCount; i++) {
                    System.out.println(productNames[i]+ " : " + productPrices[i] + "원");
                }
                //종료
            } else if (options == 3) {
                System.out.println("프로그램을 종료합니다.");
                break;
            } else {
                System.out.println("올바른 옵션을 선택하세요.");
            }
        }


    }
}

해결

앞서 options값을 받으려고 사용했던 scanner.nextInt()는 정수를 입력받고 개행 문자를 버퍼에 남겨두는데 nextLine()은 개행 문자를 입력으로 받아들이기 때문에 곧바로 빈 문자열을 반환함.

System.out.println("1. 상품등록 | 2. 상품목록 | 3.종료\n메뉴를 선택하세요:");
int options = scanner.nextInt();
scanner.nextLine(); // nextInt()후에 nextLine()을 호출해서 버퍼를 비워주면됨.

//상품등록
if (options == 1) {
    if (productCount >= maxProducts) {
        System.out.println("더 이상 상품을 등록할 수 없습니다.");
        continue;
    }
	System.out.println("상품 이름을 입력하세요: ");
	productNames[productCount] = scanner.nextLine();

	System.out.println("상품 가격을 입력하세요: ");
	productPrices[productCount] = scanner.nextInt();

	productCount++;
profile
시간이 걸릴 뿐 내가 못할 건 없다.

0개의 댓글