강의

멘토링

커뮤니티

Inflearn Community Q&A

tofhs916938's profile image
tofhs916938

asked

Kim Young-han's Java Tutorial - Your First Step into Java with Code

ScannerWhileEx2 질문

Resolved

Written on

·

233

·

Edited

0

 

package scanner.ex;

import java.util.Scanner;

public class ScannerWhileEx1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        while(true){
            System.out.print("이름을 입력하세요 (종료를 입력하면 종료): ");
            String name = scanner.nextLine();

            if(name.equals("종료")){
                System.out.println("프로그램을 종료합니다.");
                break;
            }

            System.out.print("나이를 입력하세요: ");
            int age = scanner.nextInt();
            scanner.nextLine(); //숫자 입력 후의 줄바꿈 처리

            System.out.println("입력한 이름: " + name + ", 나이: " + age);
        }
    }
}
package scanner.ex;

import java.util.Scanner;

public class ScannerWhileEx2 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        while(true){
            System.out.print("상품의 가격을 입력하세요 (-1을 입력하면 종료): ");
            int price = input.nextInt();
            //input.nextLine();
            if(price == -1){
                System.out.println("프로그램을 종료합니다.");
                break;
            }
            System.out.print("구매하려는 수량을 입력하세요: ");
            int num = input.nextInt();
            //input.nextLine();

            System.out.println("총 비용: " + price * num);
        }
    }
}

ScannerWhileEx1에서는 숫자 입력 뒤 줄바꿈 처리를 해줘야한다고 배웠는데

ScannerWhileEx2에서는 숫자 입력 뒤 줄바꿈 처리를 하지 않아도 오류가 안생깁니다.

두 문제의 차이가 궁금합니다.

문자열과 숫자가 입력될 때만 줄바꿈 처리를 해주는건가요?

java객체지향

Answer 1

0

안녕하세요. 깡인한님, 공식 서포터즈 y2gcoder입니다.

다음 링크(클릭) 을 참고해주십쇼! 줄바꿈에 대한 입력 버퍼를 비워주는 행위 input.nextLine() 는 nextInt 후 남아있을 줄바꿈 문자(\n)를 nextLine() 에서 받아버려서 발생할 버그를 방지해주기 위해서 넣어주고 있습니다.

ScannerWhileEx2 와 같이 nextInt()만 반복해서 입력할 때, nextInt()는 입력 버퍼에서 숫자만 받아 사용하기 때문에 위의 행위를 해주지 않아도 괜찮습니다!

감사합니다.

tofhs916938님의 프로필 이미지
tofhs916938
Questioner

감사합니다.

tofhs916938's profile image
tofhs916938

asked

Ask a question