Careeroza
Real World Example
Electricity Bill with Slabs
State electricity boards charge by slabs: the first units are cheap, later units cost more. Billing systems implement this with if / else if chains.
Example
public class Main {
public static void main(String[] args) {
int[] readings = {80, 180, 420};
for (int units : readings) {
double bill;
if (units <= 100) {
bill = units * 3.0;
} else if (units <= 200) {
bill = 100 * 3.0 + (units - 100) * 4.5;
} else if (units <= 400) {
bill = 100 * 3.0 + 100 * 4.5 + (units - 200) * 6.0;
} else {
bill = 100 * 3.0 + 100 * 4.5 + 200 * 6.0 + (units - 400) * 8.0;
}
double fixedCharge = units > 300 ? 100 : 50;
System.out.printf("%3d units -> energy Rs. %7.2f + fixed Rs. %.0f = Rs. %.2f%n",
units, bill, fixedCharge, bill + fixedCharge);
}
}
}Output
80 units -> energy Rs. 240.00 + fixed Rs. 50 = Rs. 290.00 180 units -> energy Rs. 660.00 + fixed Rs. 50 = Rs. 710.00 420 units -> energy Rs. 2110.00 + fixed Rs. 100 = Rs. 2210.00