不同类别的难度运行方法

时间:2013-11-13 21:24:35

标签: java class methods

我正在创建一个简单的程序来设置对象的标题和名称: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这两行都找到了“找不到符号”。这本书已被实例化,我无法弄清楚这个问题。

提前致谢!

1 个答案:

答案 0 :(得分:1)

您已将参数book1String)声明为与实例变量book1相同的名称(Book)。要引用实例变量,请将参数命名为其他变量名,或使用this.指定实例变量:

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

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