0

我正在制作一个简单的程序来设置对象的标题和名称: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.settitlebook1.setauthor. 这本书已经实例化,我无法弄清楚问题所在。

提前致谢!

4

1 回答 1

1

您将参数book1(a ) 声明为与实例变量(a )String相同的名称。要引用实例变量,请将参数命名为不同的变量名称,或用于指定实例变量:book1Bookthis.

this.book1.setTitle(titleFinal);    //**
this.book1.setAuthor(authorFinal);  //***

无论哪种方式,您都需要创建一个实际Book实例,否则您的实例变量book1将保留null,您将获得一个NullPointerException.

于 2013-11-13T21:30:10.813 回答