
Define a class ElectricBill with the following specifications: Class name: ElectricBill Instance variables / data members: String n - to store the name of the customer int units - to store the number of units consumed double bill - to store the amount to be paid Member functions: void accept() - to accept the name of the customer and number of units consumed void calculate() - to calculate the bill as per the following tariff: Number of units Rate per unit First 100 units Rs. 2.00 Next 200 units Rs. 3.00 Above 300 units Rs. 5.00 A surcharge of 2.5% is charged if the number of units consumed is above 300 units. void print() - to print the details as follows: Name of the customer: ... Number of units consumed: ... Bill amount: ... Write a main() method to create an object of the class and call the above methods.
Topic: Class with slab tariff and surcharge
Answer
import java.util.Scanner;
class ElectricBill { String n; int units; double bill;
void accept() { Scanner sc = new Scanner(System.in); System.out.print("Enter customer name : "); n = sc.nextLine(); System.out.print("Enter units consumed : "); units = sc.nextInt(); }
void calculate() { if(units <= 100) bill = units * 2.0; else if(units <= 300) bill = 100 * 2.0 + (units - 100) * 3.0; else { bill = 100 * 2.0 + 200 * 3.0 + (units - 300) * 5.0; bill = bill + bill * 2.5 / 100; } }
void print() { System.out.println("Name of the customer: " + n); System.out.println("Number of units consumed: " + units); System.out.println("Bill amount: " + bill); }
public static void main(String args[]) { ElectricBill ob = new ElectricBill(); ob.accept(); ob.calculate(); ob.print(); } }
The electricity-bill question is the classic cumulative-slab problem, and it appears in some form almost every year.
The slabs ADD UP. A customer using 400 units does not pay 400 x 5; the first 100 are charged at 2, the next 200 at 3, and only the remaining 100 at 5: 100 x 2 = 200 200 x 3 = 600 100 x 5 = 500 subtotal = 1300
The surcharge is applied ONLY in the highest branch, and only after the subtotal is complete: bill = bill + bill * 2.5 / 100 gives 1300 + 32.50 = Rs. 1332.50. Putting the surcharge outside the if, or applying it to every customer, is the commonest error.
Note the boundary wording: "above 300" means strictly greater, so 300 units exactly falls in the middle slab and attracts no surcharge. Write units <= 300 for that branch.
Check the other slabs too: 80 units gives Rs. 160, and 250 units gives 200 + 450 = Rs. 650.
n String - name of the customer units int - number of units consumed bill double - amount payable, computed slab-wise sc Scanner - object used to read input ob ElectricBill - object of the class used in main()