-3

So I'm practictising Object oriented programming and I'm trying to make a Book class that can have multiple authors but I don't know how to do it. This is the UML of the excerise: enter image description here

This is my author class which works fine:

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 + "]";
    }
}

And here is the Book class that I tried to make:

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();
    }
}

So when I try to make an object of a book in my main.java the constructor of the book class is not working. Also at this function : public Author getAuthors() { it says: Array index is out of bounds. Also at the methods to get the author names, emails and genders it says: Unknown class authors[].

How can I modify this book class so a book can have one or more authors? (the Book class did work when a book only could have 1 author, but now I'm trying to change it so a book can have more authors)

Any kind of help is appreciated!

johnny
  • 135
  • 2
  • 4
  • 12
  • 1
    Have a look into ArrayList. – rustyx Dec 02 '18 at 10:49
  • where is your main method, where you execute the app. please provide the code for that ! – Mehdi Dec 02 '18 at 10:49
  • You can use an `ArrayList`, it can let you have dynamic number of authors for a book. – PradyumanDixit Dec 02 '18 at 10:50
  • Try to use `List` https://docs.oracle.com/javase/8/docs/api/java/util/List.html instead of array, first. – Aleksandr Podkutin Dec 02 '18 at 10:50
  • This code wouldn't compile. I don't see how you could run it and get a runtime exception. Use the standard way of defining an array: `private Author[] authors = new Author[2];`. The variable *name* is `authors*. The variable *type* is `Àuthor[]`. It's thus an array if Authors, and arrays don't have any `getName()` method. Your three last methods don't make sense: how could a method returning**multiple** author names return a **single** String? – JB Nizet Dec 02 '18 at 10:54

2 Answers2

0

it says: Array index is out of bounds

First, it cannot say that with the given code, because it doesn't compile with the last three methods.

And well, authors.length == 2, and your array only has indicies 0 and 1

If you want to actually "get the authors", you want to return the array, not a specific one

public Author[] getAuthors() {
    return authors;
}

And if you did want to get one, then add the index.

It's also good habit to add boundary checking

public Author getAuthor(int index) {
    return (index < 0 || index >= authors.length) ? null : authors[index];
}

However, with these fixes, you might see null now because you actually have two list; the one you will pass to new Book(), and the field within the instance of that object.

Rather, you will want to do

private Authors[] authors;

public Book(String name, Author authors[], double price, int qty) {
    this.name = name;
    this.authors = authors;

And in the main method create the authors

Author[] authors = new Author[] {
    new Author("Tan Ah Teck", "AhTeck@somewhere.com", 'm'),
    new Author("Paul Tan", "Paul@nowhere.com", 'm')
};
Book b = new Book("name", authors, ...);
System.out.println(Arrays.toString(b.getAuthors()));

Also at the methods to get the author names, emails and genders it says: Unknown class authors[]

Because authors[].blah is not valid syntax. You need to loop over each of the array values to get the respective fields.

I would suggest Arrays.stream methods and StringJoiner for handling this

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Hello, thanks it works but now I want to make a function on how to call the author names, is there an example on how to use array.stream and stringjoiner? – johnny Dec 02 '18 at 11:39
  • 1
    Stick with arrays and for loops instead for now and wait with streams until you have learned the basics. – Joakim Danielson Dec 02 '18 at 11:55
  • @johnny https://stackoverflow.com/questions/38425623/java-join-array-of-primitives-with-separator – OneCricketeer Dec 02 '18 at 16:59
0

When you don't provide this keyword for authors within your constructor, the code works with your constructor parameter not with your class variable, therefore you encounter that problem.

try removing the authors from constructor like this:

public Book(String name, double price, int qty)
Mehdi
  • 3,795
  • 3
  • 36
  • 65
  • The array reference is modified, so just the parameter is not altered... – OneCricketeer Dec 02 '18 at 10:57
  • @cricket_007 he has problem understanding the concept, this way he can figure our what is going on and I believe he's gonna be able to solve his problems afterwards – Mehdi Dec 02 '18 at 11:01
  • You could rather just have `this.authors = authors;`, like the other fields, and remove `new Author[2]` from the field – OneCricketeer Dec 02 '18 at 11:02
  • @cricket_007 it's not a good solution because he might pass an array with length 1 and after he adds two elements within his constructor, IndexOutOfBoundException will occur ! – Mehdi Dec 02 '18 at 11:04
  • No? If you add two elements into the constructor, then the length of the array is then the same size as the parameter array... And you cannot add elements to arrays – OneCricketeer Dec 02 '18 at 11:08
  • @cricket_007 what I am saying is that he might mistakenly pass an array with length 1 as constructor parameter array. I think you still didn't get me – Mehdi Dec 02 '18 at 11:10
  • I don't see any issue with that as long as the code compiles and still matches the requirements – OneCricketeer Dec 02 '18 at 11:13
  • @cricket_007 Imagine you have this code inside your main method -> new Book("Name", new Author [1], 100.0, 5); and in your constructor you have this code -> this.authors = authors; now if you do this -> authors[0] = new Author("Tan Ah Teck", "AhTeck@somewhere.com", 'm'); authors[1] = new Author("Paul Tan", "Paul@nowhere.com", 'm'); You will get IndexOutOfBoundException. Therefore this approach is not a good approach. He has to use a dynamic approach, something like a list OR remove that constructor parameter! – Mehdi Dec 02 '18 at 11:20
  • No, no :) I was saying replace the `authors[0]` and `authors[1]` calls with that – OneCricketeer Dec 02 '18 at 11:21
  • 1
    @cricket_007 of course if he removes those authors[0] and authors[1], that would be okay! are you kidding me ? – Mehdi Dec 02 '18 at 11:22
  • Look at the excercise instruction (uml) in the question, the constructor should take an array and that array is what determines how many authors you can have. Strange design but that’s the way the requirements are – Joakim Danielson Dec 02 '18 at 11:48