Define a class named BookFair with the following description: [15]
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 Rs 1000 2% of price
More than Rs 1000 and less than or equal to Rs 3000 10% of price
More than Rs 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.
Solution
TC++ #7316
import java.util.Scanner;
public class BookFair {
private String Bname;
private double price;
public BookFair() {
Bname = null;
price = 0.0;
}
public void Input() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter book name: ");
Bname = scanner.nextLine();
System.out.print("Enter price: ");
price = scanner.nextDouble();
}
public void calculate() {
double discountPercentage = 0;
if (price <= 1000) { discountPercentage = 2; } else if (price > 1000 && price <= 3000) { 25 discountPercentage = 10; 26 } else if (price > 3000) {
discountPercentage = 15;
}
price = price - (price * discountPercentage / 100);
}
public void display() {
System.out.println("Name: " + Bname);
System.out.println("Price after discount: " + price);
}
public static void main(String[] args) {
BookFair bookFair = new BookFair();
bookFair.Input();
bookFair.calculate();
bookFair.display();
}
}
Sample output
Enter book name: How to Java
Enter price: 2500
Name: How to Java
Price after discount: 2250.0