C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Class & Object Based Program - Electric Bill - Java Programs

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

₹ 2.00

Next 200 units

₹ 3.00

Above 300 units

₹ 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.

 

import java.util.Scanner; class ElectricBill{ String n; int units; double bill; public void accept(){ Scanner in = new Scanner(System.in); System.out.print("Customer name: "); n = in.nextLine(); System.out.print("Units consumed: "); units = Integer.parseInt(in.nextLine()); } public void calculate(){ if(units <= 100) bill = units * 2.0; else if(units <= 300) bill = 200 + (units - 100) * 3.0; else{ bill = 800 + (units - 300) * 5.0; bill += 2.5 / 100 * bill; } } public 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 obj = new ElectricBill(); obj.accept(); obj.calculate(); obj.print(); } }

Output

 
 OUTPUT 1: 
Customer name: Rocky
Units consumed: 125
Name of the customer: Rocky
Number of units consumed: 125
Bill amount: 275.0 

 OUTPUT 2: 
Customer name: Ronnie
Units consumed: 350
Name of the customer: Ronnie
Number of units consumed: 350
Bill amount: 1076.25