Bookstore Statistician
Submit solution
Points:
10 (partial)
Time limit:
1.0s
Memory limit:
256M
Authors:
Problem type
Allowed languages
Java 19, Java 8
題目說明
請撰寫一個書店管理程式,程式功能包括允許使用者新增書籍,依照關鍵字判斷書籍分類,書店在收錄圖書時,只會收下書籍分類不為Other
且價格大於0的書,收錄完成後,計算並顯示所有書本數量,所有書本總價,並找出最長的書本標題,以及最短的書本標題。
輸出格式為"Total books: " + totalBooks + "; Total price: " + totalPrice + "; Longest title: " + longestTitle + "; Shortest title: " + shortestTitle
,可參考以下範例。
若有兩本書籍標題長度一樣,則採用較早加入書店的書籍作為答案。在測試資料中,至少會有一本合格的書籍,且每一本書籍的標題至少有一個字。
可以利用以下的參考程式碼作為基礎,做小幅度的修改和補充(可能在20
行以內),讓它可以滿足以上需求。若修改正確,當程式獲得以下每一組範例輸入時,應該產生該範例的對應輸出結果。
範例輸入#1
Java Programming;199
Italian Cooking;250
Java Stories;150
World War II Biography;400
Python Cookbook;601
範例輸出#1
Total books: 4; Total price: 1350; Longest title: World War II Biography; Shortest title: Java Stories
範例輸入#2
JavaScript Essentials;600
Mediterranean Adventure;501
Historical Figures;400
Sci-Fi Adventures;450
Mystery Tales;300
範例輸出#2
Total books: 3; Total price: 1551; Longest title: Mediterranean Adventure; Shortest title: Sci-Fi Adventures
參考程式碼
import java.util.ArrayList;
import java.util.Scanner;
class Book {
private String title; // title of the book
private int price; // price of the book
public Book(String title, int price) {
this.title = title;
this.price = price;
}
public String getTitle() {
return title;
}
public int getPrice() {
return price;
}
public String toString() {
return "Title: " + title + ", Price: " + price + ", Category: " + getCategory();
}
public String getCategory() {
if (title.contains("Java") || title.contains("Python")) {
return "Programming";
} else if (title.contains("Cookbook") || title.contains("Food")) {
return "Cooking";
} else if (title.contains("Biography") || title.contains("Culture")) {
return "History";
} else if (title.contains("Adventure") || title.contains("Horror")) {
return "Fiction";
} else {
return "Other";
}
}
}
class BookStore {
// a variable to store the books in the library
private ArrayList<Book> library;
// constructor to initialize the library as an empty list
public BookStore() {
library = new ArrayList<>();
}
// a method to add a book to the library
public void add(Book book) {
if (book.getPrice() > 0 && !book.getCategory().equals("Other")) {
library.add(book);
}
}
}
public class MyProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// create a new BookStore object, where the library contains some books
BookStore store = new BookStore();
// Allow the user to add 5 books to the store
for (int i = 1; i <= 5; i++) {
// Example input: Java Programming;25
// (title: Java Programming, price: 25)
String input = scanner.nextLine();
String title = input.split(";")[0];
int price = Integer.parseInt(input.split(";")[1]);
// create a new Book object with the given title and price
store.add(new Book(title, price));
}
// print the statistics of the library
System.out.println(store.getStatistics());
}
}
Comments