Challenge: Count the Objects
Completed
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
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
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module