我是 Java 新手。尝试做一个简单的库,但遇到了问题。
"Exception in thread "main" java.lang.NullPointerException at Book.showData(Book.java:22) at Book.main(Book.java:28) Java Result: 1"
我知道如何用一种方法完成这项工作。但是当我使用两种方法——一种读取数据,另一种显示数据时,我得到了一个错误。我认为我没有正确引用字符串矩阵,但我真的不知道如何修复它。
import java.util.Scanner;
public class Book {
int bookID;
String bookName;
String bookAuthor;
int publishDate;
public String readData(){
Scanner scanner = new Scanner(System.in);
System.out.println("Book's name: ");
this.bookName = scanner.nextLine();
System.out.println("\nAuthor's name: ");
this.bookAuthor = scanner.nextLine();
System.out.println("\nYear of publish: ");
this.publishDate = scanner.nextInt();
return bookAuthor;
}
public void showData(){
String[] names = bookAuthor.split(" ");
System.out.println(bookName+" author is "+String.format("%s %s", names[0], names[names.length-1]));
}
public static void main(String args[]){
new Book().readData();
new Book().showData();
}
}
最佳答案
您正在创建 Book
对象的两个实例。因此,当您在第二个上调用 showData
时,您的字符串未初始化(对象的默认值为 null
),因此当您尝试拆分时会抛出 NPE在 bookAuthor
变量上。
您必须创建一个 Book
实例,然后对其执行操作。
Book b = new Book();
b.readData(); //<-- here you initialize the value fields for this instance (the instance b)
b.showData(); //<-- it's ok to use them now, they have been initialized !
关于java - 线程 "main"java.lang.NullPointerException 中的异常 - 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20539976/