Home / Programs / Define a class named BookFair with the following description:
Programming Example

Define a class named BookFair with the following description:

👁 156 Views
💻 Practical Program
📘 Step by Step Learning
Study this program carefully to understand the logic, output, and explanation in a structured way.

Information & Algorithm

Define a class named BookFair with the following description:

Instance variables/Data members:
String Bname — stores the name of the book
double price — stores the price of the book

Member methods:
(i) BookFair() — Default constructor to initialize data members
(ii) void Input() — To input and store the name and the price of the book.
(iii) void calculate() — To calculate the price after discount. Discount is calculated based on the following criteria.

Price Discount
Less than or equal to ₹1000 2% of price
More than ₹1000 and less than or equal to ₹3000 10% of price
More than ₹3000 15% of price

(iv) void display() — To display the name and price of the book after discount.

Write a main method to create an object of the class and call the above member methods.

Program Code

import java.util.Scanner;

public class BookFair
{
    private String bname;
    private double price;

    public BookFair() {
        bname = "";
        price = 0.0;
    }

    public void input() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter name of the book: ");
        bname = in.nextLine();
        System.out.print("Enter price of the book: ");
        price = in.nextDouble();
    }

    public void calculate() {
        double disc;
        if (price <= 1000)
            disc = price * 0.02;
        else if (price <= 3000)
            disc = price * 0.1;
        else
            disc = price * 0.15;

        price -= disc;
    }

    public void display() {
        System.out.println("Book Name: " + bname);
        System.out.println("Price after discount: " + price);
    }

    public static void main(String args[]) {
        BookFair obj = new BookFair();
        obj.input();
        obj.calculate();
        obj.display();
    }
}

Output

Enter name of the book: Java the ultimate
Enter price of the book: 2081
Book Name: Java the ultimate
Price after discount: 1872.9
Press any key to continue . . .


How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.