Java |找不到符号 |返回一个对象
Java | Cannot Find Symbol | Returning An Object
我在返回我创建的对象书时遇到问题,我们将不胜感激任何帮助。该程序正在询问一本书,然后是一位作者,并将其存储在一个对象(书)中。然后将其保存到书籍数组中。
**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) {
}
}**
不要在 if/else 中定义 book 对象,只需在 if 之外定义它,例如:
book definedBook = new book();
if (..) {
//setter
} else {
//setter
...
}
return definedBook;
移动 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);
}
我在返回我创建的对象书时遇到问题,我们将不胜感激任何帮助。该程序正在询问一本书,然后是一位作者,并将其存储在一个对象(书)中。然后将其保存到书籍数组中。
**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) {
}
}**
不要在 if/else 中定义 book 对象,只需在 if 之外定义它,例如:
book definedBook = new book();
if (..) {
//setter
} else {
//setter
...
}
return definedBook;
移动 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);
}