Define a class ElectricBill with the following specifications:

Java Programming Language (Article) (Program)

21

Define a class ElectricBill with the following specifications:

class : ElectricBill

Instance variables / 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 be paid

Member methods:
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% 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 member methods.

Program:

import java.util.Scanner;

public class ElectricBill
{
    private String n;
    private int units;
    private double bill;
    
    public void accept() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter customer name: ");
        n = in.nextLine();
        System.out.print("Enter units consumed: ");
        units = in.nextInt();
    }
    
    public void calculate() {
        if (units <= 100)
            bill = units * 2;
        else if (units <= 300)
            bill = 200 + (units - 100) * 3;
        else {
            double amt = 200 + 600 + (units - 300) * 5;
            double surcharge = (amt * 2.5) / 100.0;
            bill = amt + surcharge;
        }
    }
    
    public void print() {
        System.out.println("Name of the customer\t\t: " + n);
        System.out.println("Number of units consumed\t: " + units);
        System.out.println("Bill amount\t\t\t: " + bill);
    }
    
    public static void main(String args[]) {
        ElectricBill obj = new ElectricBill();
        obj.accept();
        obj.calculate();
        obj.print();
    }
}

Output:

Enter customer name: Rumman Ansari
Enter units consumed: 123
Name of the customer            : Rumman Ansari
Number of units consumed        : 123
Bill amount                     : 269.0
Press any key to continue . . .

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.