
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 functions: BookFair() - default constructor to initialize data members void input() - to input and store the name and the price of the book 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 1000 and up to Rs. 3000 10% of price More than Rs. 3000 15% of price 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 methods.
Topic: Class with default constructor and discount slabs
Answer
import java.util.Scanner;
class BookFair { String bName; double price;
BookFair() { bName = ""; price = 0.0; }
void input() { Scanner sc = new Scanner(System.in); System.out.print("Enter book name : "); bName = sc.nextLine(); System.out.print("Enter price : "); price = sc.nextDouble(); }
void calculate() { if(price <= 1000) price = price - price * 2.0 / 100; else if(price <= 3000) price = price - price * 10.0 / 100; else price = price - price * 15.0 / 100; }
void display() { System.out.println("Book name : " + bName); System.out.println("Price after discount : " + price); }
public static void main(String args[]) { BookFair ob = new BookFair(); ob.input(); ob.calculate(); ob.display(); } }
A percentage-discount class. Note that the WHOLE price is discounted at a single rate decided by its band — there is no adding of lower slabs as in an electricity bill.
Order the conditions from the lowest band upwards. Because else-if stops at the first true test, reaching the second branch already guarantees the price is above 1000, so price <= 3000 alone suffices.
The constructor is explicitly demanded, so write it with no return type and set bName to "" and price to 0.0 as required.
One design point worth noticing: calculate() overwrites price with the discounted value. That satisfies the question, but it destroys the original price — if the display had to show BOTH the original and the discounted amount, a separate variable would be needed. Mentioning that shows real understanding.
Check: a book at Rs. 500 attracts 2% and costs Rs. 490; at Rs. 2000 it attracts 10% and costs Rs. 1800; at Rs. 5000 it attracts 15% and costs Rs. 4250.
bName String - name of the book price double - price of the book, replaced by the discounted price sc Scanner - object used to read input ob BookFair - object of the class used in main()