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.
(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.
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.
Answer:
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.10;
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();
}
}