如何打印出薪水最高和第二高的员工详细信息?

时间:2019-12-25 07:27:31

标签: arraylist

csv文件,其中有3个条目,分别是empname,emp id,designation和薪金Robert,33,Manager,12000 Duval,23,Associate,6000 Kierron,33,AD,20000

从下面的代码中,如何打印出薪水最高和第二高的员工详细信息?

enter code here

公共类HighSalary {

public static void highSalary() throws IOException {
    String record;
    BufferedReader br = new BufferedReader(new FileReader("/Users/ak/Documents/emp.csv"));

    System.out.println("\t\t  Printing Employee Details of Highest & Second Highest Salary \n");

    System.out.println(" ------------------------------------------------------------- ");
    System.out.println("|   ID      Name                Age         Address           |");
    System.out.println(" ------------------------------------------------------------- ");

    List<List<String>> arlist = new ArrayList<>();

    int highestSal = 0;
    int secondSal = 0;

    while ((record = br.readLine()) != null) {

        String[] words = record.split(",");

        arlist.add(Arrays.asList(words));

        int salary = Integer.parseInt(words[3]);
        if (highestSal == 0) {
            highestSal = salary;
            secondSal = salary;
        }
        else if (salary > highestSal) {
            secondSal = highestSal;
            highestSal = salary;
        }
        else if (salary > secondSal || secondSal == 0) {
            secondSal = salary;
        }
    }
    System.out.println("highest salary: " + highestSal);
    System.out.println("second highest salary: " + secondSal);
    br.close();
}

}

enter code here

1 个答案:

答案 0 :(得分:0)

您可以迭代文件,跟踪最高和第二高的工资。分配新的最高工资时,应将第二高的工资分配给先前的最高工资。另外,您可以为与最高和第二高薪雇员相关的元数据存储两个字符串。

Integer highest = null;
Integer second = null;
String highEmp = "";
String secondEmp = "";

while ((record = br.readLine()) != null) {
    String[] words = record.split(",");
    arlist.add(Arrays.asList(words));

    int salary = Integer.parseInt(words[3]);
    if (highest == null) {
        highest = salary;
        second = salary;
        highEmp = record;
        secondEmp = record;
    }
    else if (salary > highest) {
        second = highest;
        secondEmp = highEmp;
        highest = salary;
        highEmp = record;
    }
    else if (salary > second) {
        second = salary;
        secondEmp = record;
    }
}

System.out.println("highest salary: " + highest);
String[] parts = highEmp.split(",");
System.out.println("Name: " + parts[0] + ", Age: " + parts[1] + ", Desig: " + parts[2]);
System.out.println("second highest salary: " + second);
parts = secondEmp.split(",");
System.out.println("Name: " + parts[0] + ", Age: " + parts[1] + ", Desig: " + parts[2]);