Challenge: Count the Objects

Lab Java Beginner 10 points

Write a class Book with a title, a constructor, a toString() that returns Book: <title>, and a static counter of how many books were created. Read n and then n titles (one per line). Print each book, then Total books: <count> using the static counter.

Input

First n, then n lines, each a book title.

Output

n book lines, then the total.

Example

Input

2
The Hobbit
Wings of Fire

Output

Book: The Hobbit
Book: Wings of Fire
Total books: 2
Sample input available Sample output available
Editor
Java

Hints

Read n with Integer.parseInt(sc.nextLine().trim()) so the titles can be read with nextLine().

Add count++ inside the constructor.

Printing an object calls its toString().

Solution explanation

The static count is shared, so every constructor call adds to the same number.

Show solution
import java.util.Scanner;

class Book {
    static int count = 0;
    String title;

    Book(String title) {
        this.title = title;
        count++;
    }

    @Override
    public String toString() {
        return "Book: " + title;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.nextLine().trim());
        for (int i = 0; i < n; i++) {
            System.out.println(new Book(sc.nextLine()));
        }
        System.out.println("Total books: " + Book.count);
    }
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD