[英]In Java, using a Scanner to read in data from a .txt file so I can generate objects with that data as constructor parameters
[英]How can i read certain grouped attributes of objects from a .txt file and calculate their totals in Java?
我是Java的新手,正在为此工作而苦苦挣扎。 我需要使用“ Employees.txt”文件为完成的所有对象创建一个消息框。 我遇到的问题是使用“ Manager”,“ Sales”和“ Admin”卷获取员工对象,并让他们的“薪水”合计平均值并通过MessageDialog显示出来。 并将其写入新的.txt文件。 我不能使用数组,因为它还没有涉及。 有人能够帮助我并解释我做错了什么吗?
public class PayrollReport
{
public static void main(String[] args) throws IOException
{
Employee emp;
FileReader fr = new FileReader("Employees.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("Summary");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
String input = "";
int empId;
String name, pos;
double sal;
double count = 0.0;
double total = 0.0;
//for(int i=0; i<=35; i++)
//{
pos = br.readLine();
while(pos != null)
{
sal = Double.parseDouble(br.readLine());
sal += sal;
count++;
pos = br.readLine();
emp = new Employee(Integer.parseInt(br.readLine()), br.readLine(), br.readLine(), Double.parseDouble(br.readLine()));
input += emp.toString();
}
br.close();
total=sal/count;
JOptionPane.showMessageDialog(null, "EMPLOYEE LIST\n\n" + input);
}`enter code here`
}
您在这里要做的就是利用if else
类似的if else
:
double managersTotalSalary = 0;
double adminsTotalSalary = 0;
...
int managersCount = 0;
int adminsCount = 0;
...
while(... ) {
...
if ("Manager".equals(employee.getDesignation())) {
managersCount ++;
managersTotalSalary += employee.getSalary();
} else if ("Admin".equals(employee.getDesignation())) {
....
}
...
}
//you have count and total salary, calculate average and display it.
很简单,您只需要创建一个Scanner类的对象,并将诸如此类的fileReader对象传递给扫描器对象的构造函数即可
Scanner s= new Scanner(fr);
empId=s.nextInt();
name= s.nextLine();
pos=s.nextLine();
您的employee.txt应该采用这种格式
2安舒尔头
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.