Given this class:
public class Book {
private String bookName;
private String[] chapters = new String[9];
private int numberOfChapters;
public Book(String bn){
bookName = bn;
}
public Book(String b[]){
chapters = b;
}
public void addChapter(String chapter){
chapters[numberOfChapters] = chapter;
numberOfChapters++;
}
public String[] getChapter(){
return chapters;
}
public int getNumberOfChapters(){
return numberOfChapters;
}
public String getBookName(){
return bookName;
}
public String toString(){
return("Book Name: " + getBookName() + " chapters[] = " + getChapter() + " number of chapters : " + getNumberOfChapters());
}
}
I need to write a driver that creates an array of chapters (strings), then assigns each object within it to the Book object. My problem is that when I do this, the toString() method doesn't print the chapters properly, and instead returns the memory address.
Here's what I have so far:
public class BookTest {
public static void main(String[] args) {
String[] BookArray = new String[9];
for(int i = 0; i<BookArray.length; i++){
BookArray[i] = new String("Chap"+(i+1));
}
Book b1 = new Book("Name1");
for(int i=0; i<BookArray.length; i++){
b1.addChapter(BookArray[i]);
}
System.out.println(b1.toString());
}
}
Which prints
Book Name: Name1 chapters[] = [Ljava.lang.String;@2a139a55 number of chapters : 9
What do I need to change in my driver to properly print the chapters, without changing the toString() method?
List<String>rather than aString[].