Java |无法找到符号|返回一个对象

时间:2015-02-23 05:14:36

标签: java object return symbols

我在返回已创建的对象书时遇到问题,我们非常感谢任何帮助。该程序要求一本书然后是作者,并存储在一个对象(书)中。然后将其保存到一系列书籍中。

**import java.util.*;
public class BookShop {
    public static void main(String[] args) {
        Scanner kybd = new Scanner(System.in);
        book[] books = new book[10];

        for (int i = 0; i < books.length; i++){
            books[i] = getBook(kybd);
        }

        printBookDetails(books);
    }

    private static book getBook(Scanner kybd) {
        System.out.print("What Is The Title Of The Next Book?:>   ");
        String title = kybd.nextLine();

        System.out.print("Who Is The Author Of The Next Book?:>   ");
        String author = kybd.nextLine();

        if(author == null){
            book definedBook = new book();
            definedBook.setTitle(title);
        }
        else{
            book definedBook = new book();
            definedBook.setTitle(title);
            definedBook.setAuthor(author);
        }

        return definedBook;

    }

    private static void printBookDetails(book[] books) {

    }
}**

2 个答案:

答案 0 :(得分:3)

不是在if / else中定义book对象,而是在if之外定义它,如:

book definedBook = new book();

 if (..) {
     //setter   
 } else {
  //setter
    ...
 }
 return definedBook;

答案 1 :(得分:1)

移动book的声明,使其具有范围

book definedBook = new book();
if (author == null){
    // book definedBook = new book();
    definedBook.setTitle(title);
} else{
    // book definedBook = new book();
    definedBook.setTitle(title);
    definedBook.setAuthor(author);
}