【发布时间】:2019-05-03 21:43:27
【问题描述】:
所以我正在练习面向对象的编程,我正在尝试制作一个可以有多个作者的 Book 类,但我不知道该怎么做。 这是练习的UML:
这是我的作者类,效果很好:
public class Author {
//attributen van de class auteur
private String name;
private String email;
private char gender;
//constructor
public Author (String name, String email, char gender){
this.name = name;
this.email = email;
this.gender= gender;
}
//methodes
public String getName(){
return name;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public char getGender(){
return gender;
}
//methode om gegevens van autheur opbject op te halen
public String toString(){
return "Author[name = " + name + ", email = " + email + ", gender = " + gender + "]";
}
}
这是我尝试制作的 Book 类:
public class Book {
//attributes
private String name;
private Author authors [] = new Author[2];
private double price;
private int qty = 0;
public Book(String name, Author authors[], double price, int qty) {
this.name = name;
authors[0] = new Author("Tan Ah Teck", "AhTeck@somewhere.com", 'm');
authors[1] = new Author("Paul Tan", "Paul@nowhere.com", 'm');
this.price = price;
this.qty = qty;
}
public String getName() {
return name;
}
public Author getAuthors() {
return authors[authors.length];
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public String toString() {
return "Book [name = " + name + " authors = " + authors[0] + " email = " + authors[0].getEmail() + " price = " + price + " qty = " + qty + "]";
}
//methodes om gegevens van de autheur op te halen
public String getAuthorNames() {
return authors[].getName();
}
public String getAuthorEmails() {
return authors[].getEmail();
}
public char getAuthorGenders() {
return authors[].getGender();
}
}
因此,当我尝试在 main.java 中创建书的对象时,书类的构造函数不起作用。
也在这个功能:public Author getAuthors() {
它说:数组索引超出范围。
同样在获取作者姓名、电子邮件和性别的方法中,它说:Unknown class authors[]。
如何修改此图书类别,以便一本书可以有一个或多个作者? (当一本书只能有 1 个作者时,Book 类确实有效,但现在我正在尝试更改它,以便一本书可以有更多作者)
感谢任何形式的帮助!
【问题讨论】:
-
看看 ArrayList。
-
你的主要方法在哪里,你在哪里执行应用程序。请提供代码!
-
您可以使用
ArrayList<Author>,它可以让您拥有一本书的动态作者数量。 -
首先尝试使用
Listdocs.oracle.com/javase/8/docs/api/java/util/List.html 而不是数组。 -
这段代码无法编译。我看不出您如何运行它并获得运行时异常。使用定义数组的标准方法:
private Author[] authors = new Author[2];。变量name是authors*. The variable *type* isÀauthor[]. It's thus an array if Authors, and arrays don't have anygetName()`方法。您的最后三个方法没有意义:返回多个作者姓名的方法如何返回单个字符串?
标签: java arrays class oop object