0

我需要帮助来了解如何编写诸如“如果已设置,则执行此操作”之类的语句之类的方法。例如,我写了一个 Author 和一个 Book 类。在我的 Book 类中,我需要一个返回书名的方法。但是,如果已经设置了书的作者(即 Book 中有设置作者的方法),则返回书名加上作者姓名。

这是我对这些类的一些代码

public class Author{
  String authorFirstName;
  String authorLastName;
  int authorBirth;
  int authorDeath;

  //creates a new author object with nothing set
  public Author(){
  }

  //String l=last name, String f=frist name
  //creates new author object by setting the last and first name
  public Author(String l, String f){
    authorLastName=l;
    authroFirstName=f;
  }
//end of Author class
 } 

public class Book{
  int bookYearPublish;
  Author bookAuthor;
  String bookNumberISBN;
  String bookTitle;

  public Book(){
  }

  //String t is the title of the book
  //creats a Book object with a title
  public Book(String t){
    bookTitle=t;
  }

  //String t is the title of the book
  //Author a is the author of the book
  //creats a Book object with a title and author
  public Book(String t, Author a){
    bookTitle=t;
    bookAuthor=a;
  }

  //Author a is the author that will be set for the Book
  //sets the author of the book
  public void setAuthor(Author a){
    bookAuthor=a;
  }

  //returns the Author of the Book
  public Author getAuthor(){
    return bookAuthor;
  }

  //returns the title of Book
  //if the author is known returns a String in the form of title. last name, first name of author
  //if the year is known returns a String in the form title (year). last name, first name of author
  public String toString(){
    String title=bookTitle;
    if(bookAuthor.equals(this.getAuthor())){//I am getting a NullPointException here so this is where my problem is
      title=title+". "+bookAuthor;
    }
    if(bookYearPublish.equals(this.getYear())){
      title=bookTitle+" ("+bookYearPublish+"). "+bookAuthor;
    }
    return title;
  }

  //ends class Book
}
4

3 回答 3

0

只需使用类似这样的方法编写一个 getTitle() 方法(如 getAuthor 方法)

 public string getTitle()
{
  String s = this.title;
if(author != "" || author != null)
{
s+=this.author;
}
return s;
}
于 2013-11-08T17:22:08.100 回答
0

代替:

if(bookAuthor.equals(this.getAuthor())){

if(bookAuthor != null && bookAuthor.equals(this.getAuthor())){

但是,我认为这不是你想要的......this.getAuthor()返回bookAuthor所以它应该总是匹配......我认为你真正想要的是:

if( bookAuthor != null) {
    title=title+". "+bookAuthor;
}
于 2013-11-08T17:22:18.177 回答
0

只需尝试在您设置作者后执行您想要执行的操作,setAuthor(Author a)如下所示:

public void setAuthor(Author a){
bookAuthor=a;

// put the action here.
}
于 2013-11-08T17:43:47.303 回答