gpt4 book ai didi

JAVA,从文本文件中读取,从数组中打印出信息

转载 作者:太空宇宙 更新时间:2023-11-04 13:59:26 25 4
gpt4 key购买 nike

对 Java 很陌生,我有一个问题

我收到了一个文本文件,要求找到收入最高的员工,并打印出他们的信息(fName、Lname、ID)

文本文件是这样的:

Date of birth fName lName    wage hr   work emp ID  
12/03/1929 Detzk Fyshe 37 49 07036310484
04/17/1930 Cauus Walden 38 52 63612537553
07/12/1930 Barth Harling 43 72 42101524036
07/16/1930 Bartl Barnhill 43 62 48621748867

我设法找到最高工资。但不知道如何打印出信息

这是我到目前为止的代码:

public static void main(String[] args) {

File inFile = new File ("dataSet.txt");
ArrayList <String> inData = new ArrayList <String>();


String strline;


try
{
FileInputStream fstream = new FileInputStream(inFile);
BufferedReader br = new BufferedReader (new InputStreamReader (fstream));
while ((strline = br.readLine()) != null)
{
strline = strline.trim();
if ((strline.length()!=0)) inData.add(strline);
}


} catch (Exception e) {
System.err.println("Error CANNOT FIND FILE!");
}


// Max wage finder *start*

int maxWage=0;
for (int i=0; i<inData.size(); i++){

String [] word = inData.get(i).split(" ");
int wage=Integer.parseInt (word[3]);
int hrWork=Integer.parseInt (word[4]);
int earn = wage*hrWork;

if (earn>maxWage){
maxWage=earn;
}
}
System.out.println("Max Wage in $:"+maxWage);

//max wage finder *end*

最佳答案

如果您正在读取员工数据,则问题的面向对象解决方案是创建一个 Employee 类,该类具有强类型(日期为 Dates,整数为 ints)属性,用于对文件内容进行建模。

除了存储每个Employee的实际数据的实例变量之外,您可能还需要重写类中的toString()方法,以便可以轻松输出员工信息,例如输出到System.out。此外,您还需要一个获取员工“总工资”的 getter(用 wage * hrWork 计算),以便可以在外部比较两个员工的工资,例如通过 Comparator .

总而言之,相关部分的代码可能如下所示:

private static final DateFormat FORMATTER = new SimpleDateFormat("MM/dd/yyyy");
...
List<Employee> employees = new ArrayList<Employee>();
...
// within the loop that reads the file:
String[] columns = strline.split(" ");
employees.add(new Employee(
FORMATTER.parse(columns[0]), // DOB,
columns[1], // first name
columns[2], // last name
Integer.parseInt(columns[3]), // wage
Integer.parseInt(columns[4]), // hr
columns[5]) // employee id
);
...
// after all lines have been read, output the employee with largest wage
Employee earnsMost = Collections.max(employees, new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return e1.getTotalSalary() - e2.getTotalSalary();
}
});

System.out.println(earnsMost + " earns most.");

关于JAVA,从文本文件中读取,从数组中打印出信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29461332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com