我正在制作一个简单的程序,用于设置对象的标题和名称: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
两行都收到“找不到符号”。这本书已实例化,我无法找出问题所在。提前致谢!
最佳答案
您将参数book1
(a String
)声明为与实例变量book1
(a Book
)相同的名称。要引用实例变量,请为参数命名不同的变量名称,或使用this.
指定实例变量:
this.book1.setTitle(titleFinal); //**
this.book1.setAuthor(authorFinal); //***
无论哪种方式,您都需要创建一个实际的
Book
实例,否则您的实例变量book1
将保持为null
,您将得到一个NullPointerException
。关于java - 不同类别的难度运行方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19964666/