Nested Classes

Lab Java Intermediate 20 points

Create class Library with a static class Book (title, year) and an inner (non-static) class Shelf that can see the library's name. Read the library name and books, then print LIBRARY shelf: N books and the oldest book.

Input

Line 1: library name. Line 2: n. Then n lines title year.

Output

Two lines.

Example

Input

City
3
Dune 1965
Emma 1815
Neuromancer 1984

Output

City shelf: 3 books
Emma 1815
Sample input available Sample output available
Editor
Java

Hints

A static nested class doesn't need an outer object.

An inner class can use the outer object's fields.

Solution explanation

Nesting keeps helper classes next to the class they belong to.

Show solution
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class Library {
    final String name;
    final Shelf shelf = new Shelf();

    Library(String name) {
        this.name = name;
    }

    static class Book {
        final String title;
        final int year;

        Book(String title, int year) {
            this.title = title;
            this.year = year;
        }
    }

    class Shelf {
        final List<Book> books = new ArrayList<>();

        String summary() {
            return name + " shelf: " + books.size() + " books";
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Library lib = new Library(sc.next());
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            lib.shelf.books.add(new Library.Book(sc.next(), sc.nextInt()));
        }
        Library.Book oldest = lib.shelf.books.get(0);
        for (Library.Book b : lib.shelf.books) {
            if (b.year < oldest.year) oldest = b;
        }
        System.out.println(lib.shelf.summary());
        System.out.println(oldest.title + " " + oldest.year);
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD