晚上好(ish?)我现在正在为课程创建一个程序,为3本书分配3组标题/作者。我有一个读书班,一个测试班和一个赞助人班。到目前为止,顾客已经从测试人员那里正确地收集了名字并返回了它。问题出在顾客类,roweBook方法上。测试人员将初始化标题和名称,创建一个赞助人,然后尝试打印借款书方法的布尔结果。我将标题和作者从测试仪发送到赞助商的browerBook中,尽管当clickBook方法尝试设置标题时,我一直收到nullpointerexception,但我假设对ranchBook中所有其他与作者和标题相关的方法也是如此。任何建议深表感谢!
测试人员类别:
public class ProjectFiveSix {
public static void main(String[] args) {
String title = "On the Origin of Species";
String name = "Hugo";
String author = "Charles Darwin";
Patron patronOne = new Patron();
System.out.print("The Patron's Name is: " + patronOne.getName(name));
System.out.print("Test " + patronOne.borrowBook(author, title));
赞助人类别:
public class Patron {
private String name;
private Book book1;
private Book book2;
private Book book3;
public Patron(){
name = "";
book1 = null;
book2 = null;
book3 = null;
}
public String getName(String name){
return name;
}
public boolean borrowBook(String title, String author){
if (book1 == null){
book1.getTitle(title);
book1.getAuthor(author);
return true;
}else if (book2 == null){
book2.getTitle(title);
book2.getAuthor(author);
return true;
}else if (book3 == null){
book3.getTitle(title);
book3.getAuthor(author);
return true;
}else{
return false;
}
}
public String toString(String str){
str = name + "\n" + book1;
return str;
}
}
书类:
public class Book {
private String title;
private String author;
public Book(){
title = "";
author = "";
}
public String getTitle(String title){
title = title;
return title;
}
public String getAuthor(String author){
author = author;
return author;
}
}
正如许多人建议的那样,我尝试将roweBook的书设置为!= null,并且在某种程度上起作用。在公共Patron(){中,每本书均设置为null,因此该方法将为false。说得通!但是,这样做的想法是,每本书都将以null开始,并且在运行roweBook时,它将为书中找到的第一本空书分配title和author的当前值。我想我可以进行设置,以便如果roweBook返回false,则将值分配给Book1,尽管我不相信该方法可以用于第二本书和第二本书,因为它每次都将返回true。非常感谢社区,你们是很大的帮助!
已回答-使用-本-书中的内容减少了冗余,并会在我行进时修改值,很好的解决!谢谢您的帮助,创作一本新书也很有意义而且很有效。
最佳答案
将您的Book
构造函数更改为此
public Book(String title, String author){
this.title = title;
this.author = author;
}
在这种方法中,您应该创建一个
Book
public boolean borrowBook(String title, String author){
if (book1 == null){
book1 = new Book(title, author);
book1.getTitle(title); // I don't know what you need these for?
book1.getAuthor(author); // ???
return true;
}else if (book2 == null){
book2 = new Book(title, author);
book2.getTitle(title);
book2.getAuthor(author);
return true;
}else if (book3 == null){
book3 = new Book(title, author);
book3.getTitle(title);
book3.getAuthor(author);
return true;
}else{
return false;
}
}
关于java - 找不到NullPointerException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19991720/