Write a class “Book” to model books. This book object will have two instance var
ID: 3699206 • Letter: W
Question
Write a class “Book” to model books. This book object will have two instance variables: a title (String) and authors (Array of Strings). Write a default constructor which sets title to “Test” and authors to null. Write a constructor receiving values for these fields. Lastly, implement getter and setter methods for your instance variables. In “Book”, write a method “bookToString”, which returns a string with the books information (in the format below. Use ” to have a quote character in a string. “The Lord of the Rings” by J.R.R. Tolkien “Nixonland” by Rick Perlstein “Berenstain Bears” by Stan Berenstain & Jan Berenstain
Explanation / Answer
Please find my code :
Book.java
public class Book {
private String title;
private String authors[];
public Book() {
this.title="Test";
authors=null;
}
public Book(String title, String[] authors) {
super();
this.title = title;
this.authors = authors;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String[] getAuthors() {
return authors;
}
public void setAuthors(String[] authors) {
this.authors = authors;
}
public String bookToString()
{
String str="";
if(authors.length>1)
for(int i=0;i<authors.length;i++)
{
str+="""+title+"" by "+authors[i];
if(i!=authors.length-1)
{
str+="&";
}
}
else
{
str+="""+title+"" by "+authors[0];
}
return str;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.