Electricity Bill Calculator in Java

Calculate electricity bill based on units consumed using slab rates.

IntermediateModule 2: Conditional ProgramsExample 10 of 20
electricity-bill-calculator.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6
7 System.out.print("Enter units consumed: ");
8 int units = sc.nextInt();
9
10 double bill;
11 if (units <= 100) {
12 bill = units * 1.5;
13 } else if (units <= 200) {
14 bill = 100 * 1.5 + (units - 100) * 2.0;
15 } else {
16 bill = 100 * 1.5 + 100 * 2.0 + (units - 200) * 3.0;
17 }
18
19 System.out.println("Total bill = " + bill);
20
21 sc.close();
22 }
23}

Output

Enter units consumed: 250
Total bill = 500.0

What's going on

We apply different per-unit rates depending on the slab the consumption falls into.