exception in thread "main" java.util.nosuchelementexception

박영준·2023년 4월 21일
0

Troubleshooting

목록 보기
3/29

1. 상황

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();		// 추가
        
        for(int i = 0; i < n; i++) {
            for(int j = 0; j <= i; j++) {
                System.out.print("*");
            }
            
            System.out.println();
        }
    }
}
  • int m = sc.nextInt(); 를 추가할 경우, nosuchelementexception 오류가 발생했다.

2. 원인

  • 더이상 Element가 없는데도 불러오려고 할 때 발생

  • Scanner가 읽어올 스트림이 없는데도 읽으려고 해서 발생한 오류

  • Stream을 닫아주는(close) 곳이 있기 때문에 발생
    → 닫아주게 되면, System.in이 종료돼버린다.

3. 해결법

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        
        for(int i = 0; i < n; i++) {
            for(int j = 0; j <= i; j++) {
                System.out.print("*");
            }
            
            System.out.println();
        }
    }
}
  • 객체를 하나만 사용하도록 한다.

참고: [오류] Exception in thread "main" java.util.NoSuchElementException

profile
개발자로 거듭나기!

0개의 댓글