반응형
Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

배움과 기록의 장

[백준] 11718번: 그대로 출력하기 (Java) 본문

problem solving

[백준] 11718번: 그대로 출력하기 (Java)

chaeunii 2023. 3. 1. 02:45

✅ 문제

https://www.acmicpc.net/problem/11718

 

✅ 풀이

  •  처음에는 while 문을 아래와 같이 작성했더니, NoSuchElement 라는 런타임에러가 떴다. 
while(true) {
            String line = sc.nextLine();
            if (line == null) break;
            else System.out.println(line);
        }

  • 찾아보니 nextLine() 메서드에서 다음 입력값이 없으면 null 값이 들어갈 줄 알았는데, 그게 아니라 에러를 띄우고 끝낸다는 것이었다.
  • 따라서 hasNextLine() 메서드를 통해 다음 입력값이 있는지를 확인한 후, true면 입력을 받고 출력을 진행해야한다.

 

✅ 코드

import java.util.Scanner;

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

        while(sc.hasNextLine()) {
            String line = sc.nextLine();
            System.out.println(line);
        }
    }
}

 

 

 

 

참고링크

반응형