LearnFrenzy
Sign in Take a free test

Java Basics, Syntax and Data Types · Java Basics Programs · Question 8

Electricity bill with slab rates in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Compute an electricity bill for given units: first 100 units at ₹3.50, next 100 at ₹5.00, next 100 at ₹6.50 and above 300 at ₹8.00, plus a fixed charge of ₹50 and 5% tax; print a breakdown.

Solution
Main.java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        final double[] RATES = {3.50, 5.00, 6.50, 8.00};
        final int SLAB = 100;
        while (in.hasNextInt()) {
            int units = in.nextInt(), left = units;
            double energy = 0;
            for (int i = 0; i < RATES.length && left > 0; i++) {
                int used = (i == RATES.length - 1) ? left : Math.min(left, SLAB);
                energy += used * RATES[i];
                left -= used;
            }
            double subtotal = energy + 50;
            double tax = subtotal * 0.05;
            System.out.printf("%4d units: energy %8.2f + fixed 50.00 + tax %6.2f = Rs %8.2f%n", units, energy, tax, subtotal + tax);
        }
    }
}

Output Verified by compiling and running

  75 units: energy   262.50 + fixed 50.00 + tax  15.63 = Rs   328.13
 180 units: energy   750.00 + fixed 50.00 + tax  40.00 = Rs   840.00
 300 units: energy  1500.00 + fixed 50.00 + tax  77.50 = Rs  1627.50
 425 units: energy  2500.00 + fixed 50.00 + tax 127.50 = Rs  2677.50

An array of rates and a loop replace a long if/else ladder; the last slab takes all remaining units. printf rounds for display (15.625 → 15.63).

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links