Polymorphic Payroll
Completed
Create interface Payable { double pay(); String id(); } implemented by Salaried(monthly), Hourly(rate, hours) (overtime over 160 hours paid ×1.5) and Contractor(invoice). Read workers, print each id pay (2 decimals), sorted by pay descending.
Input
n, then lines S id monthly, H id rate hours, C id invoice.
Output
n lines.
Example
Input
3 S ann 4000 H bob 20 170 C cy 3500.5
Output
ann 4000.00 cy 3500.50 bob 3500.00
Editor
Java
Hints
Store everything as Payable; each class decides how it is paid.
Solution explanation
The sorting and printing code never needs to know which kind of worker it's handling.
Show solution
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
interface Payable {
double pay();
String id();
}
class Salaried implements Payable {
final String id; final double monthly;
Salaried(String id, double monthly) { this.id = id; this.monthly = monthly; }
public double pay() { return monthly; }
public String id() { return id; }
}
class Hourly implements Payable {
final String id; final double rate, hours;
Hourly(String id, double rate, double hours) { this.id = id; this.rate = rate; this.hours = hours; }
public double pay() {
double overtime = Math.max(0, hours - 160);
return rate * (hours - overtime) + rate * 1.5 * overtime;
}
public String id() { return id; }
}
class Contractor implements Payable {
final String id; final double invoice;
Contractor(String id, double invoice) { this.id = id; this.invoice = invoice; }
public double pay() { return invoice; }
public String id() { return id; }
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<Payable> workers = new ArrayList<Payable>();
for (int i = 0; i < n; i++) {
String kind = sc.next();
String id = sc.next();
if (kind.equals("S")) {
workers.add(new Salaried(id, sc.nextDouble()));
} else if (kind.equals("H")) {
workers.add(new Hourly(id, sc.nextDouble(), sc.nextDouble()));
} else {
workers.add(new Contractor(id, sc.nextDouble()));
}
}
Collections.sort(workers, new Comparator<Payable>() {
public int compare(Payable a, Payable b) {
return Double.compare(b.pay(), a.pay());
}
});
for (Payable p : workers) {
System.out.printf("%s %.2f%n", p.id(), p.pay());
}
}
}