想法是打印出一条简单的行,说明书名,作者和价格。但是,即使构造了Book对象,我似乎也无法返回任何值。
我正在构建Book类,Author类,并使用测试器来运行程序。
这是我在看的东西:
package book;
public class Book {
String title;
Author author;
double price;
public Book(String title, Author author, double price){}
public Book(){}
public void setbookTitle(String title) {
this.title = title;
}
public void setPrice(double price) {
this.price = price;
}
public String getTitle() {
return title;
}
public Author getAuthor() {
return author;
}
public double getPrice() {
return price;
}
}
package book;
public class Author {
String name;
String email;
char gender;
public Author(String name, String email, char gender){
}
public String getName() {
return name;
}
public String getEmail(){
return email;
}
public char getGender(){
return gender;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public void setGender(char gender) {
this.gender = gender;
}
@Override
public String toString(){
return name;
}
}
package book;
public class BookTester {
public static void main(String[] args) {
Author author1 = new Author("Horstmann", "horstmann@gmail.com", 'm');
Book book1 = new Book("Big Java", author1, 60);
Double number = book1.getPrice();
System.out.println(number);
System.out.println ("The Book information is: ");
System.out.println(book1.getTitle() + book1.getAuthor() + book1.getPrice());
}
}
任何建议将不胜感激!
答案 0 :(得分:1)
它为null,因为您没有在Book&Author的构造函数中做任何事情:
public Author(String name, String email, char gender){
}
public Book(String title, Author author, double price){
}
您需要设置值并将其更新为对象的值:
public Author(String name, String email, char gender){
this.name = name;
this.email = email;
this.gender = gender;
}
public Book(String title, Author author, double price){
this.title = title;
this.author = author;
this.price = price;
}
答案 1 :(得分:1)
您应该将构造函数更改为
public Book(String title, Author author, double price){
this.title = title;
this.author = author;
this. price = price;
}
public Author(String name, String email, char gender){
this.name = name;
this.email = email;
this.gender = gender;
}