LearnFrenzy
Sign in Take a free test

Classes and Objects · Classes and Objects Programs · Question 9

Employee payroll and department summary in Java Solution, output & explanation

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

Create Employee objects (name, department, monthly salary), give a 10% raise to one department, and print each department's head count and total salary.

Solution
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

class Employee {
    String name, dept;
    double salary;
    Employee(String name, String dept, double salary) { this.name = name; this.dept = dept; this.salary = salary; }
    void raise(double percent) { salary += salary * percent / 100; }
}

public class Main {
    public static void main(String[] args) {
        List<Employee> staff = new ArrayList<>(List.of(
            new Employee("Asha", "IT", 80000), new Employee("Ravi", "HR", 45000),
            new Employee("Meena", "IT", 72000), new Employee("John", "Sales", 50000), new Employee("Zoya", "HR", 48000)));

        for (Employee e : staff) if (e.dept.equals("HR")) e.raise(10);

        Map<String, double[]> summary = new TreeMap<>();       // dept -> {count, total}
        for (Employee e : staff) {
            double[] s = summary.computeIfAbsent(e.dept, k -> new double[2]);
            s[0]++;
            s[1] += e.salary;
        }
        summary.forEach((dept, s) -> System.out.printf("%-6s %d staff, total %,.0f%n", dept, (int) s[0], s[1]));
    }
}

Output Verified by compiling and running

HR     2 staff, total 102,300
IT     2 staff, total 152,000
Sales  1 staff, total 50,000

The raise loop changes the Employee objects in place; the summary reads the updated values. TreeMap keeps departments sorted.

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