简体   繁体   中英

How can i read certain grouped attributes of objects from a .txt file and calculate their totals in Java?

I'm new to Java and struggling with this assignment. I need to use the "Employees.txt" file to create a message box for all objects which I've done. Where I'm stuck is getting the employee objects with the rolls "Manager" "Sales" and "Admin" and having their "salary" total their average and display it via MessageDialog. And also write this into a new .txt file. I cannot use Arrays as it hasn't been covered yet. Is someone able to help me and explain what I'm doing wrong?

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`  
}

What you have to do here is make use of if else like:

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.

It is simple you just need to create an object of Scanner class and pass your fileReader object in constructor of scanner object something like this

Scanner s= new Scanner(fr);
empId=s.nextInt();
name= s.nextLine();
pos=s.nextLine();

your employee.txt should be in this format

2 Anshul head

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM