007-001-002

Class Creation: Book Information Manager

Medium

Problem Description

[Explanation]

🎯 Problem Overview

In this problem, you will create a Book class that manages book information. You'll learn how to use the basic elements of a class: fields, constructors, and methods, and understand how to encapsulate data. By displaying information in a table format, the execution results become visually clear, allowing you to see how the class actually works.

📚 Prerequisites

Knowledge required to solve this problem:

What is a Class

A class is a blueprint for objects. In architecture, it's like a "blueprint"; in cooking, it's like a "recipe". By defining a class, you can create multiple objects with the same structure.

Fields (Instance Variables)

Fields are data that a class holds. In this problem, we define four fields: title, author, price, and pages. Fields are usually declared as private to prevent direct access from outside the class.

Constructor

A constructor is a special method automatically called when creating an instance of a class. It has the same name as the class and doesn't specify a return type. The role of a constructor is to set initial values to fields.

Method

Methods define actions (processes) that a class has. In this problem, the getInfo() method returns book information in table format. Methods are declared as public to be callable from outside the class.

💡 Key Points

1. Field Definition

Define four fields to hold book information. Fields are declared as private and accessible only within the class.

private String title;   // Book title
private String author;  // Author name
private int price;      // Price
private int pages;      // Page count
```java

### 2. Initialization in Constructor
The constructor accepts four parameters and assigns values to each field. Using the this keyword distinguishes between parameters and fields.

```java
public Book(String title, String author, int price, int pages) {
    this.title = title;   // this.title is field, title is parameter
    this.author = author;
    this.price = price;
    this.pages = pages;
}
```java

### 3. Implementing getInfo() Method
The getInfo() method creates a table-formatted string using values stored in fields and returns it. The newline character (\n) is used to create a multi-line string.

### 4. Error Handling
If price or pages are negative, an error message is returned. This allows appropriate handling of invalid data.

## 📖 Code Explanation (Step by Step)

### Step 1: Class and Field Definition
```java
public class Book {
    private String title;
    private String author;
    private int price;
    private int pages;
```java
Define a public class named Book. Declare four private fields to hold book information. Making them private prevents direct access from outside the class, maintaining data integrity.

### Step 2: Constructor Implementation
```java
public Book(String title, String author, int price, int pages) {
    this.title = title;
    this.author = author;
    this.price = price;
    this.pages = pages;
}
```java
The constructor is defined with the same name as the class, "Book". It accepts four parameters and assigns values to each field. The this keyword means "of this object" and is used to distinguish fields from parameters.

### Step 3: Input Validation
```java
if (price < 0) {
    return "Error: Price must be positive";
}
if (pages < 0) {
    return "Error: Pages must be positive";
}
```java
At the beginning of the getInfo() method, check if price and pages are not negative. If a negative value is found, return an error message and end processing. This is called the "early return pattern", which makes code more readable by handling error cases first.

### Step 4: Creating Table-Formatted String
```java
return "====================\n" +
       "Book Information\n" +
       "====================\n" +
       "Title  : " + title + "\n" +
       "Author : " + author + "\n" +
       "Price  : " + price + "yen\n" +
       "Pages  : " + pages + "pages\n" +
       "====================";
```java
Create a table-formatted string using string concatenation (+ operator). \n is a newline character, making the execution result multi-line. Using border lines (=) makes the information more readable.

## ⚠️ Common Mistakes

### 1. Writing Return Type in Constructor
```java
// ❌ Wrong
public void Book(String title, String author, int price, int pages) {
    // ...
}

// ✅ Correct
public Book(String title, String author, int price, int pages) {
    // ...
}
```java
**Reason**: Constructors don't have a return type. Writing void or any other type makes it a regular method instead of a constructor.

### 2. Assigning to Fields Without this Keyword
```java
// ❌ Wrong
public Book(String title, String author, int price, int pages) {
    title = title;  // Just reassigning parameter
    author = author;
}

// ✅ Correct
public Book(String title, String author, int price, int pages) {
    this.title = title;  // Assigning to field
    this.author = author;
}
```java
**Reason**: Without this, when parameter and field names are the same, you're just reassigning the parameter, and the field doesn't get set.

### 3. Forgetting Newline Characters
```java
// ❌ Wrong (everything on one line)
return "Book Information" + "Title: " + title + "Author: " + author;

// ✅ Correct (with newlines for readability)
return "Book Information\n" + "Title: " + title + "\n" + "Author: " + author;
```java
**Reason**: Without newline characters (\n), all information gets concatenated on one line, making it hard to read.

## 🚀 Advanced Topics

Hints for deeper learning:

### 1. Adding Accessor Methods (getter/setter)
Currently, fields are private so they can't be accessed directly from outside. By adding methods like getTitle() or setPrice(), you can safely retrieve and modify field values.

### 2. Multiple Constructors (Overloading)
You can define multiple constructors. For example, adding a constructor that doesn't require price and pages allows more flexible instance creation.

### 3. Overriding toString() Method
By overriding the toString() method instead of getInfo(), you can display information directly with System.out.println(book).

### 4. More Complex Validation
Beyond checking if price is not negative, you can add more detailed validation like checking if title is not empty or if page count is within a reasonable range.

## 🔗 Related Learning Topics

Topics to learn next or concepts related to this problem:

- **Accessor Methods (getter/setter)** (Category 008-002)
- **Method Overloading** (Category 009)
- **Inheritance and Polymorphism** (Category 010)
- **Encapsulation and Access Modifiers** (Category 011)
- **Relationships Between Classes (Delegation and Aggregation)** (Category 012).

Test Cases

※ Output examples follow programming industry standards

Input:
Expected Output:
Input:
Expected Output:
Input:
Expected Output:
Input:
Expected Output:
Input:
Expected Output:
Input:
Expected Output:
❌ Some tests failed
❌ エラー発生

Your Solution

Current Mode: My Code
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Write your code here

sc.close();
}
}
0 B / 5 MB

You have 9 free executions remaining