我正在创建一个简单的程序来设置对象的标题和名称:book1
。最终,我们的目标是在Patron
类下拥有几本将使用Book
类来分配值的书籍。但是,我很难让Patron
类承认Book
类方法。
基本测试员/主要方法:
import java.util.Scanner;
public class ProjectFiveSix {
public static void main(String[] args) {
String title = "Bob";
String name = "Hugo"; // name of patron (class assigning book)
String author = "Rodrigo";
Patron patronOne = new Patron();
patronOne.setName(name);
赞助人类:
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 setName(String name){
return name;
}
public String borrowBook(String book1, String titleFinal, String authorFinal, String title, String author){
if (book1 == null){
book1.setTitle(titleFinal); //**
book1.setAuthor(authorFinal); //***
}
}
}
书籍课程:
public class Book {
private String titleFinal;
private String authorFinal;
public Book(){
titleFinal = "";
authorFinal = "";
}
public String setTitle(String title){
titleFinal = title;
return titleFinal;
}
public String setAuthor(String author){
authorFinal = author;
return authorFinal;
}
}
我在book1.settitle
和book1.setauthor
这两行都找到了“找不到符号”。这本书已被实例化,我无法弄清楚这个问题。
提前致谢!
答案 0 :(得分:1)
您已将参数book1
(String
)声明为与实例变量book1
相同的名称(Book
)。要引用实例变量,请将参数命名为其他变量名,或使用this.
指定实例变量:
this.book1.setTitle(titleFinal); //**
this.book1.setAuthor(authorFinal); //***
无论哪种方式,您都需要创建一个实际的Book
实例,否则您的实例变量book1
将保持null
,您将获得NullPointerException
。