왜 배열을 인쇄 할 때 nullPointerException (마지막 println 참조)이 시작되는지 알 수 없습니다. 전에 nullPointException을 본 적이 있지만 배열의 끝에있었습니다. 나는 그것이 초기에 있었던 이유를 알지 못한다. 게다가 누군가가 예외를 없애는 데 도움이된다면 고맙겠습니다.배열 시작 부분에서 NullPointerException을 가져 오는 중입니까?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("Book.txt");
Scanner sc = new Scanner(file);
Book[] books = new Book[20];
int x = 0;
while(sc.hasNext()){
int id, year;
String name, author;
//scan data for each book and create new book object
id = Integer.valueOf(sc.next());
year = Integer.valueOf(sc.nextLine().trim());
name = sc.nextLine();
author = sc.nextLine();
books[x] = new Book(id, name, year, author);
x++;
}
for(Book b : books){
System.out.println(b.toString());
}
}
}
처음과 끝이 아니라 어떻게 알 수 있습니까? 20 권 미만의 책을 입력하면 프로그램이 NPE로 중단되고, 20 권이 넘는 책이 입력되면 Index Out of Bound로 충돌합니다. – dasblinkenlight
NPE가 없으면 정확히 어떤 줄을 나타내는지, null인지는 알 수 없습니다. 데이터에 대한 가정이나 디버거를 사용하기 위해 printlns를 두는 것은 어떻습니까? –