Answer on Question #50962, Programming, Java | JSP | JSF
Problem.
An electricity board charges the following rates to domestic users:- For the first 100 units – 40p/unit For the next 200 units – 50p/unit Beyond 300 units – 60p/unit. Write a program to read the names of users and number of units consumed and print out the charges with names. Use the concepts of classes.
Code (User.java)
public class User {
/**
* Units consumed.
*/
private float units;
/**
* User name.
*/
private String name;
/**
* Default constructor.
* @param name user name.
* @param units units consumed.
*/
public User(String name, float units) {
this.units = units;
this.name = name;
}
/**
* Print out charges with names
*/
public void printCharge() {
float charge;
if (units < 100) {
charge = units * 40;
} else if (100 <= units && units < 200) {
charge = (units - 100) * 50 + 4000;
} else {
charge = (units - 200) * 60 + 5000 + 4000;
}
System.out.format("Name: %s Charge: %.2f\n", name, charge);
}
}Code (Main.java)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input
String name = sc.next();
User[] users = new User[5];
int size = 0;
while (!name.equals("end")) {
float units = sc.nextFloat();
users[size] = new User(name, units);
name = sc.next();
size++;
}
}
// Output
for(int i = 0; i < size; i++) {
users[i].printCharge();
}
}
}Output.
name1 120
name2 210
name3 400
end
Name: name1 Charge: 5000,00
Name: name2 Charge: 9600,00
Name: name3 Charge: 21000,00
http://www.AssignmentExpert.com/
Comments