Skip to content
Java project #08Beginner

Electricity Bill Calculator

Slab-based tariffs for domestic and commercial customers, fixed charges, duty, late-payment surcharges, rounding and a billing summary — modelled with an enum.

Estimated time
~3 hours to build
Files
4 files · 278 lines
Technologies
Java 21, Enums with fields, Records, Streams

Introduction

Electricity bills use progressive slabs: the first units are cheap and each slab beyond costs more. Implementing that correctly — plus duty, surcharges and rounding — is a realistic exercise in loops, enums and careful integer money arithmetic.

Problem statement

Read meter readings for several customers (consumer id, name, tariff, previous and current reading, days late). Reject unknown tariffs, malformed numbers, negative days and readings that go backwards. For each valid line compute energy charges slab by slab (domestic: 0–100, 101–200, 201–300, above 300; commercial: 0–200, above 200), add a fixed charge and 6% duty, add a 1.5% surcharge for every started 15-day period late, round to whole rupees and print an itemised bill. Finish with a summary of totals, the highest consumer and averages per tariff.

Objectives

  • Represent tariffs as an enum with data
  • Implement slab calculations with a loop
  • Keep money exact using long paise
  • Produce itemised, aligned output

Features

  • Two tariffs with different slabs and fixed charges
  • Itemised energy charges per slab
  • Duty, late surcharges and rounding lines
  • Validation and a billing summary

Concepts demonstrated

  • Enums with constructors
  • Progressive (slab) calculation
  • Integer money arithmetic
  • Validation
  • Aggregation

System architecture

Tariff is an enum whose constants carry slab limits, paise-per-unit rates and a fixed charge. compute walks the slabs, charging min(remaining, slab size) × rate for each and recording a Line record for the bill, then adds fixed charge, duty, surcharge and rounding lines. parseTariff matches tariff names case-insensitively with a friendly error. main validates each line, prints each Bill, and summarises with streams.

Folder structure

TextProject tree
electricity-bill-calculator/
├── README.md
├── src/Main.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Main.java

115 lines
Javasrc/Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Electricity Bill Calculator — reads meter readings for several customers and computes
* slab-based energy charges for domestic and commercial tariffs, a fixed charge, electricity
* duty and a late-payment surcharge, then prints itemised bills and a summary.
*
* Input lines: CONSUMER_ID NAME TARIFF PREVIOUS_READING CURRENT_READING DAYS_LATE
*/
public class Main {
enum Tariff {
DOMESTIC(new int[]{100, 200, 300}, new long[]{350, 500, 680, 800}, 5_000),
COMMERCIAL(new int[]{200}, new long[]{750, 950}, 15_000);
final int[] limits; // slab upper limits in units
final long[] rates; // paise per unit for each slab (one more than limits)
final long fixed; // fixed monthly charge in paise
Tariff(int[] limits, long[] rates, long fixed) {
this.limits = limits;
this.rates = rates;
this.fixed = fixed;
}
}
static final double DUTY_RATE = 0.06; // 6% on energy charges
static final double LATE_RATE = 0.015; // 1.5% of the bill per 15 days late (or part)
record Line(String label, long paise) { }
record Bill(String id, String name, Tariff tariff, int units, List<Line> lines, long total) { }
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
List<Bill> bills = new ArrayList<>();
int lineNo = 0;
while (in.hasNextLine()) {
String raw = in.nextLine().trim();
lineNo++;
if (raw.isEmpty() || raw.startsWith("#")) continue;
String[] p = raw.split("\\s+");
try {
if (p.length != 6) throw new IllegalArgumentException("expected 6 fields");
Tariff t = parseTariff(p[2]);
int prev = Integer.parseInt(p[3]), curr = Integer.parseInt(p[4]), late = Integer.parseInt(p[5]);
if (curr < prev) throw new IllegalArgumentException("current reading is lower than the previous one");
if (late < 0) throw new IllegalArgumentException("days late can't be negative");
Bill b = compute(p[0], p[1], t, curr - prev, late);
bills.add(b);
print(b);
} catch (IllegalArgumentException e) { // includes NumberFormatException and unknown tariffs
System.out.println("Line " + lineNo + " rejected: " + (e instanceof NumberFormatException ? "readings must be whole numbers" : e.getMessage()));
System.out.println();
}
}
if (bills.isEmpty()) return;
long total = bills.stream().mapToLong(Bill::total).sum();
int units = bills.stream().mapToInt(Bill::units).sum();
Bill top = bills.stream().max((a, b) -> Integer.compare(a.units(), b.units())).get();
System.out.println("SUMMARY: " + bills.size() + " bills, " + units + " units, total " + rupees(total));
System.out.println("Highest consumption: " + top.name() + " (" + top.units() + " units)");
for (Tariff t : Tariff.values()) {
long n = bills.stream().filter(b -> b.tariff() == t).count();
if (n > 0) System.out.println(" " + t + ": " + n + " bill(s), average " + rupees(bills.stream().filter(b -> b.tariff() == t).mapToLong(Bill::total).sum() / n));
}
}
static Tariff parseTariff(String text) {
for (Tariff t : Tariff.values())
if (t.name().equalsIgnoreCase(text)) return t;
throw new IllegalArgumentException("unknown tariff '" + text + "' (use domestic or commercial)");
}
static Bill compute(String id, String name, Tariff t, int units, int daysLate) {
List<Line> lines = new ArrayList<>();
long energy = 0;
int remaining = units, lower = 0;
for (int i = 0; i < t.rates.length && remaining > 0; i++) {
int upper = i < t.limits.length ? t.limits[i] : Integer.MAX_VALUE;
int inSlab = Math.min(remaining, upper - lower);
long cost = inSlab * t.rates[i];
energy += cost;
String range = i < t.limits.length ? (lower + 1) + "-" + upper : "above " + lower;
lines.add(new Line(String.format("%4d units @ Rs %.2f (%s)", inSlab, t.rates[i] / 100.0, range), cost));
remaining -= inSlab;
lower = upper;
}
long duty = Math.round(energy * DUTY_RATE);
lines.add(new Line("Fixed charge", t.fixed));
lines.add(new Line("Electricity duty 6%", duty));
long subtotal = energy + t.fixed + duty;
if (daysLate > 0) {
int periods = (daysLate + 14) / 15;
long surcharge = Math.round(subtotal * LATE_RATE * periods);
lines.add(new Line("Late surcharge (" + daysLate + " days)", surcharge));
subtotal += surcharge;
}
long rounded = (subtotal + 50) / 100 * 100; // round the payable amount to whole rupees
if (rounded != subtotal) lines.add(new Line("Rounding", rounded - subtotal));
return new Bill(id, name, t, units, lines, rounded);
}
static void print(Bill b) {
System.out.println("Consumer " + b.id() + " " + b.name() + " [" + b.tariff() + "] " + b.units() + " units");
for (Line l : b.lines()) System.out.printf(" %-42s %12s%n", l.label(), rupees(l.paise()));
System.out.printf(" %-42s %12s%n%n", "AMOUNT PAYABLE", rupees(b.total()));
}
static String rupees(long paise) {
return String.format("%sRs %,d.%02d", paise < 0 ? "-" : "", Math.abs(paise) / 100, Math.abs(paise) % 100);
}
}

What each file does

src/Main.java
The Tariff enum, compute (slabs, duty, surcharge, rounding), bill printing and the summary.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Consumer C1001 Asha [DOMESTIC] 80 units
80 units @ Rs 3.50 (1-100) Rs 280.00
Fixed charge Rs 50.00
Electricity duty 6% Rs 16.80
Rounding Rs 0.20
AMOUNT PAYABLE Rs 347.00
Consumer C1002 Ravi [DOMESTIC] 335 units
100 units @ Rs 3.50 (1-100) Rs 350.00
100 units @ Rs 5.00 (101-200) Rs 500.00
100 units @ Rs 6.80 (201-300) Rs 680.00
35 units @ Rs 8.00 (above 300) Rs 280.00
Fixed charge Rs 50.00
Electricity duty 6% Rs 108.60
Late surcharge (20 days) Rs 59.06
Rounding Rs 0.34
AMOUNT PAYABLE Rs 2,028.00
Consumer C1003 Bakery [COMMERCIAL] 570 units
200 units @ Rs 7.50 (1-200) Rs 1,500.00
370 units @ Rs 9.50 (above 200) Rs 3,515.00
Fixed charge Rs 150.00
Electricity duty 6% Rs 300.90
Rounding Rs 0.10
AMOUNT PAYABLE Rs 5,466.00
Line 5 rejected: current reading is lower than the previous one
Line 6 rejected: unknown tariff 'industrial' (use domestic or commercial)
Consumer C1006 John [DOMESTIC] 250 units
100 units @ Rs 3.50 (1-100) Rs 350.00
100 units @ Rs 5.00 (101-200) Rs 500.00
50 units @ Rs 6.80 (201-300) Rs 340.00
Fixed charge Rs 50.00
Electricity duty 6% Rs 71.40
Late surcharge (40 days) Rs 59.01
Rounding -Rs 0.41
AMOUNT PAYABLE Rs 1,370.00
SUMMARY: 4 bills, 1235 units, total Rs 9,211.00
Highest consumption: Bakery (570 units)
DOMESTIC: 3 bill(s), average Rs 1,248.33
COMMERCIAL: 1 bill(s), average Rs 5,466.00
Input
# id   name   tariff     previous current days_late
C1001 Asha   domestic   12450   12530   0
C1002 Ravi   domestic   8800    9135    20
C1003 Bakery commercial 30210   30780   0
C1004 Meera  domestic   5000    4990    0
C1005 Shop   industrial 100     200     0
C1006 John   domestic   7000    7250    40

Testing

  • Run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • Ravi uses 335 units: 350 + 500 + 680 + 280 = ₹1,810 energy, plus fixed charge, duty and a 1.5% surcharge for 20 days late.
  • John is 40 days late, which counts as three 15-day periods.
  • A backwards reading and the unknown tariff 'industrial' are rejected.

Common errors

Bills are a few paise off

Store money as long paise and round explicitly once per charge; never accumulate doubles.

Every unit is charged at the highest rate

Charge each slab only for the units that fall inside it.

Possible improvements

  • Add a time-of-day tariff with peak rates
  • Read tariffs from a configuration file
  • Generate a bill file per consumer

Additional challenges

  1. 1Add a subsidy for the first 50 units for domestic users.
  2. 2Show the cost per unit for each customer.
  3. 3Compare this month with last month's consumption.

Built and tested it yourself? Mark it to update your dashboard.