I have this method as part of my class Book public String toString() { return ti
ID: 3649155 • Letter: I
Question
I have this method as part of my class Bookpublic String toString()
{
return title + " by " + author + " (" + numPages + " pages)";
}
and I need the following method in my class Library, which is an array of Book objects:
public String toString() : returns a String representation which first displays the number of books in the library, then uses the toString function of each book object in its array to display each book it contains.
I know how to get the number of books, but I still need the code to display what each book in the array contains.
Here is a little code.
public class Book
{
private String author;
private String title;
private int numPages;
public Book()
{
title = "EMPTY";
}
public Book(String titleIn, String authorIn, int numPagesIn)
{
title = titleIn;
author = authorIn;
numPages = numPagesIn;
}
public String toString()
{
return title + " by " + author + " (" + numPages + " pages)";
}
}
-------------------------------------------------------
import java.util.Arrays;
public class Library
{
private Book[] array;
private int count;
public Library(int numBooks)
{
array = new Book [numBooks];
count=0;
}
public int getCount()
{
return count;
}
public String toString()
{
//This is the code I need!!!!
}
}
Explanation / Answer
please rate - thanks
try this
I'd test it if I had all your code
public String toString()
{String s="number of books:"+count+" ";
int i;
for(i=0;i<count;i++)
s=s+array[i]+" ";
return s;
}