Sombra Devon Sombra Devon - 8 months ago 84
Java Question

Class to return

This is the expected output:

This Book
title: The God and the Sword,
year of publication: 1975,
read: false
This Book
title: The God and the Sword,
year of publication: 1975,
read: true
This Book
title: The Light of Spirind,
year of publication: 1960,
read: false
The book has now been read: true


This is the code that I currently have, I need to write a class named Book. Could someone help me out here please? I am confused with how the first book has a title and year and then the second doesn't have a year provided.

class Test{
public static void main(String[] args){
int year = 1975;
String title = "The God and the Sword";

Book b1 = new Book(title, year);
System.out.println(b1);
b1.setRead(true);
System.out.println(b1);

title = "The Light of Spirind";
Book b2 = new Book(title);
System.out.println(b2);
b2.setRead(true);
System.out.println("The book has now been read: " + b2.isRead());
}
}

class Book{

Book(String title, int year){
System.out.println("title: " + title + ", " + "year of publication: " + year + ", " + "read: " + setRead);

}
}

Answer Source

First thing I noticed Book constructors are the main issue.

Your first constructor has two parameters title and year.

Book b1 = new Book(title, year);

But in the second constructor has one parameter title and you have missed the year. That's why you didn't get year.

Book b2 = new Book(title);

You can correct it by editing the above statement from the below statement.

Book b2 = new Book(title, year);

Second thing you try to print object like System.out.println(b2); without implementing toString() method.

Please try following code. You can get the expected output without directly using the Book() constructor.

class Test {

   public static void main(String[] args) {

      Book b1 = new Book();
      b1.setYear(1975);
      b1.setTitle("The God and the Sword");
      System.out.println(b1);
      b1.setRead(true);
      System.out.println(b1);

      Book b2 = new Book();
      b2.setTitle("The Light of Spirind");
      b2.setYear(1960);
      System.out.println(b2);
      b2.setRead(true);
      System.out.println("The book has now been read: " + b2.isRead());
   }
}

class Book {

   private boolean read;
   private int year;
   private String title;

   public boolean isRead() {
      return read;
   }

   public void setRead(boolean read) {
      this.read = read;
   }

   public int getYear() {
      return year;
   }

   public void setYear(int year) {
      this.year = year;
   }

   public String getTitle() {
      return title;
   }

   public void setTitle(String title) {
      this.title = title;
   }

   Book() {

   }

   public String toString() {
      return "This Book\ntitle: " + getTitle() + ",\n " + "year of publication: " + getYear() + ",\n " + "read: " + isRead();
   }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download