首页 > 解决方案 > 如何在 JAVA 的每个特定部门中使用员工 ID 查找最高工资?

问题描述

/* Save this in a file called Main.java to compile and test it */

/* Do not add a package declaration */
import java.util.*;
import java.io.*;

/* DO NOT CHANGE ANYTHING ABOVE THIS LINE */
/* You may add any imports here, if you wish, but only from the 
   standard library */

/* Do not add a namespace declaration */
public class Main {
    public static Map<String, Integer> processData(ArrayList<String> array) {
        /*
         * Modify this method to process `array` as indicated in the question.
         * At the end, return the appropriate value.
         *
         * Please create appropriate classes, and use appropriate data
         * structures as necessary.
         *
         * Do not print anything in this method.
         *
         * Submit this entire program (not just this method) as your answer
         */
        Map<String, Integer> retVal = new Map<String, Integer>();
        for (Employee employee : array) {
            int highSalary = retVal.get(employee.getDepartment());
            if (highSalary == null || highSalary < employee.getSalary()) {
                retVal.put(employee.getDepartment(), employee.getSalary());
            }
        }
        return retVal;
    }

    public static void main(String[] args) {
        ArrayList<String> inputData = new ArrayList<String>();
        String line;
        try {
            Scanner in = new Scanner(new BufferedReader(new FileReader("input.txt")));
            while (in.hasNextLine())
                inputData.add(in.nextLine());
            Map<String, Integer> retVal = processData(inputData);
            PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
            for (Map.Entry<String, Integer> e : retVal.entrySet())
                output.println(e.getKey() + ": " + e.getValue());
            output.close();
        } catch (IOException e) {
            System.out.println("IO error in input.txt or output.txt");
        }
    }
}

这是 input.txt 文件:

22, Rajan Anand, Engineering, 1600000
23, Swati Patil, Testing, 800000
27, Vijay Chawda, Engineering, 800000
29, Basant Mahapatra, Engineering, 600000
32, Ajay Patel, Testing, 350000
34, Swaraj Birla, Testing, 350000

我创建了一个 Employee 类并尝试使用 getter setter,但它不起作用。我该如何解决这个问题,请帮帮我

预期结果:

Engineering: 22
Testing: 23

类定义:

public class Employee {
    private int salary;
    private String department;
    private int employeeId;
    private String name;

    public Employee(int salary, String department, int employeeId, String name) {
        this.salary = salary;
        this.department = department;
        this.employeeId = employeeId;
        this.name = name;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public int getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

我专门通过封装创建了 Employee 类,但我遇到了编译错误。请帮助我解决我从过去 2 天以来一直坚持的问题。但我想在没有 Employee 类的情况下做到这一点

标签: java

解决方案


  1. 首先,您需要将文件的每一行解析为一个 Employee。
  2. 接下来,您需要弄清楚如何跟踪收入最高的员工。您将需要稍后检索他们的 ID。所以你必须存储整个对象。

而不是 a Map<String, Integer>,你会想要使用 a Map<String, Employee>。当您遍历每个员工时,您可以将当前员工与从地图中检索到的员工(按部门)进行比较。如果当前员工的薪水较高,您将用当前员工替换地图中(针对该部门)的员工。

例子

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

public class Main {
    /**
     * Convert a list of Employees into a Map of Departments with the
     * highest-earning Employee
     */
    public static Map<String, Employee> processData(List<Employee> employees) {
        // Need to store the ENTIRE Employee as the value to compare salary and
        // later retrieve the ID
        Map<String, Employee> result = new HashMap<String, Employee>();
        for (Employee employee : employees) {
            Employee currEmployee = result.get(employee.getDepartment());
            if (currEmployee == null || currEmployee.getSalary() < employee.getSalary()) {
                result.put(employee.getDepartment(), employee);
            }
        }
        return result;
    }

    /** Parse a line into an Employee */
    public static Employee parseLine(String line) {
        String[] tokens = line.split(", ");
        int id = Integer.parseInt(tokens[0], 10);     // Position 1
        int salary = Integer.parseInt(tokens[3], 10); // Position 4
        String name = tokens[1];                      // Position 2
        String department = tokens[2];                // Position 3
        return new Employee(salary, department, id, name);
    }

    /** Load a file containing Employee info */
    public static List<Employee> loadFile(String filename) throws FileNotFoundException {
        ArrayList<Employee> result = new ArrayList<Employee>();
        Scanner in = new Scanner(new BufferedReader(new FileReader(filename)));
        while (in.hasNextLine()) {
            // Parse each line into an Employee object.
            result.add(parseLine(in.nextLine()));
        }
        in.close();
        return result;
    }

    /** Write each Department's highest-earning Employee's ID */
    public static void writeData(Map<String, Employee> data, String filename) throws IOException {
        PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(filename)));
        output.print(data.entrySet().stream()
                .map(e -> e.getKey() + ": " + e.getValue().getEmployeeId())
                .collect(Collectors.joining(System.lineSeparator())));
        output.close();
    }

    /** Main entry */
    public static void main(String[] args) {
        try {
            writeData(processData(loadFile("input.txt")), "output.txt");
        } catch (IOException e) {
            System.out.println("IO error in input.txt or output.txt");
        }
    }
}

推荐阅读