Pedro Marinho
Pedro Marinho

Reputation: 37

How to initialize in the main class an Array field from a constructor in another class?

Sorry if this is a silly question or if I don't put it correctly but I'll try my best to explain what the problem is.

I am supposed to create a book Class that stores the name of a book, the ISBN, the price and the author's name. Since a book may have more than one author I'm supposed to create an Array or ArrayList for this field. Everything seems to be working fine but when I initialize the Array field as a String the IDE displays an error. Am I missing something here? Does anyone know how to fix this?

Here's my code:

public class Books {
private String bookName;
private String ISBN;
private int price;
private String [] authorsList;

public Books (String bookName, String ISBN, int price, String[] authorsList){
    this.bookName = bookName;
    this.ISBN = ISBN;
    this.price = price;
    this.authorsList = authorsList;
}

public String toString(){
    return "Book title: " + bookName +
           "\nISBN: " + ISBN + 
           "\nPrice: " + price +
           "\nAuthor: " + authorsList;  
}

}

public static void main(String[] args) {          

    Books book1 = new Books("Harry Potter","12345",10,"J. K. Rowling");

    System.out.println(book1.toString());
}

}

Upvotes: 1

Views: 537

Answers (2)

Earthx9
Earthx9

Reputation: 91

If you write System.out.println like that you can see inside of array

  System.out.println(book1.bookName + "\n" + book1.ISBN+"\n" + book1.price+"\n" +  Arrays.toString(authorsList));

You can't see it now because it's an array and if you write System.out.println(book1.toString()); this way java shows only its location.That's why you saw something like this [Ljava.lang.String;@2a139a55

or please change your toString method to this now it is showed Actually this way is better:

public String toString(){
    return "Book title: " + bookName +
           "\nISBN: " + ISBN + 
           "\nPrice: " + price +
           "\nAuthor: " + Arrays.toString(authorsList);  
}
public static void main(String[] args) {          
    Books book1 = new Books("Harry Potter","12345", 10, new String[]{"J. K. Rowling"});
    System.out.println(book1.toString()); 
}

Upvotes: 1

ManyQuestions
ManyQuestions

Reputation: 1089

Use this to initialize your array:

new String[]{"J. K. Rowling"};

You're passing a String in the constructor instead of an Array.

Upvotes: 0

Related Questions