Book Inventory Statistics


Submit solution

Points: 10 (partial)
Time limit: 1.0s
Memory limit: 64M

Author:
Problem type

題目說明

請撰寫一個程式,由使用者輸入五本書籍的資料,每本書都有三個欄位,分別是書名(title)、作者(author)、類型(genre),
輸入完畢之後,指定欄位名稱,由程式計算該欄位中每種內容各自出現幾次,最後印出每種內容以及次數,輸出時依照內容字串排序(如範例程式碼所示)。 可以利用以下的參考程式碼作為基礎,做小幅度的修改(可能在12行以內),讓它可以滿足以上需求。
若修改正確,當程式獲得以下每一組範例輸入時,應該產生該範例的對應輸出結果。


參考程式碼
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;

public class LibrarySystem {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<HashMap<String, String>> books = BookCollector.getInputData(scanner, 5);

        // Get the field name to count values
        String category = scanner.next();

        scanner.close();

        // Create an instance of BookAnalyzer and count values in a specific field
        BookAnalyzer analyzer = new BookAnalyzer(books);
        HashMap<String, Integer> result = analyzer.countValues(category);

        // Sort the result by key and print it
        Object[] keys = result.keySet().toArray();
        Arrays.sort(keys);
        for (Object key : keys) {
            System.out.println(key + ": " + result.get(key));
        }
    }
}

class BookCollector {
    // Static method to get input data from the user
    public static ArrayList<HashMap<String, String>> getInputData(Scanner scanner, int numberOfBooks) {
        ArrayList<HashMap<String, String>> books = new ArrayList<>();
        for (int i = 0; i < numberOfBooks; i++) {
            HashMap<String, String> book = new HashMap<>();
            String title = scanner.next();
            String author = scanner.next();
            String genre = scanner.next();
            book.put("title", title);
            book.put("author", author);
            book.put("genre", genre);
            books.add(book);
        }
        return books;
    }
}

class BookAnalyzer {
    private ArrayList<HashMap<String, String>> books;

    // Constructor to initialize books
    public BookAnalyzer(ArrayList<HashMap<String, String>> books) {
        this.books = books;
    }
}

輸入

輸入共 6 行,格式如下:

前 5 行:每行輸入一本書的資料,由「書名 (title)」、「作者 (author)」、「類型 (genre)」三個字串組成,以空格分隔。

第 6 行:輸入要統計的欄位名稱,其值為 title、author 或 genre 三者之一。

輸出

根據第 6 行所指定的欄位,統計該欄位中每種內容出現的次數。

每一種內容與其出現次數輸出為一行,格式為:內容: 次數

所有內容依照字典序(字串排序)排列輸出。

範例輸入#1

gatsby fitzgerald fiction
hamlet shakespeare drama
pride austen fiction
othello shakespeare drama
emma austen fiction
title

範例輸出#1

emma: 1
gatsby: 1
hamlet: 1
othello: 1
pride: 1

範例輸入#2

sherlock doyle mystery
poirot christie mystery
holmes doyle mystery
marple christie mystery
spade hammett noir
genre

範例輸出#2

mystery: 4
noir: 1

Comments

There are no comments at the moment.