Electric Bill – Slab based If Else Java Program

Define a class Electric Bill with the following specifications:

class: ElectricBill

Instance Variable/ data member:
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 paid

Member methods:
1) Void accept() – to accept the name of the customer and number of units consumed
2) 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% charged if the number of units consumed is above 300 units.
3) 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 member methods.

import java.util.Scanner;
class ElectricityBill
{
    String n;
    int units;
    double bill;
    
    void accept()
    {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the name of the customer");
        n = in.nextLine();
        System.out.println("Enter the number of units consumed");
        units = in.nextInt();
    }
    
    void calculate()
    {
        if(units<=100)
            bill = 2*units;
        else if(units>100 && units<=300) //next 200 units
            bill = 2*100 + (units-100)*3;
        else if(units>300)//above 300 units
        {
            bill = 2*100 + 3*200 + (units-300)*5;
            bill = bill + 2.5*bill/100; //surcharge 2.5%
        }
    }
    
    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[])
    {
        ElectricityBill obj = new ElectricityBill();
        obj.accept();
        obj.calculate();
        obj.print();
    }
}

Video Explanation

2 thoughts on “Electric Bill – Slab based If Else Java Program”

Leave a Comment

Your email address will not be published. Required fields are marked *