In: Computer Science
Program :
see the program screenshots for the indentation reference!
Employee.java
/*
*The employees class
*/
public class Employee
{
/*
*private data members
*/
private String firstName;
private String lastName;
private String rank;
private double salary;
/*
*parameteraized constructor
*/
public Employee(String fname,String lname,String rank,double salary)
{
this.firstName = fname;
this.lastName = lname;
this.rank = rank;
this.salary = salary;
}
/*
*Getter methods
*/
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getRank()
{
return rank;
}
public double getSalary()
{
return salary;
}
/*
*format name method with lastName, firstName
*/
public String formatName(){
return lastName + ", "+firstName;
}
/*
*method to calculate Total salary of the all employees passed as array of employee
*/
public static double totalSalary(Employee arr[], int num)
{
double total=0;
for(int i=0; i<num; i++)
{
total = total + arr[i].getSalary();
}
return total;
}
/*
*method to calculate average salary of the all employees passed as array of employee
*/
public static double averageSalary(Employee arr[], int num)
{
return totalSalary(arr,num)/num;
}
}
Prog5.java
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
import java.util.ArrayList;
public class Prog5
{
public static void main(String args[])
{
/*
Reading all lines from the employees.txt file in the arraylist of Strings
*/
ArrayList<String> lines = new ArrayList<String>();
try {
// pass the path to the file as a parameter
File file = new File("employees.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null)
{
lines.add(line);
}
} catch(Exception e) {
System.out.println(e);
}
/*
*Number of lines present in the file
*/
int num = lines.size();
/*
*Creating the array of employees
*/
Employee employees[] = new Employee[num];
/*
*for each of the line in the employees.txt
*create the Employee object
*/
int i=0;
for(String line : lines)
{
String tokens[] = line.split(" ");
employees[i] = new Employee(tokens[0], tokens[1], tokens[2], Double.parseDouble(tokens[3]));
i++;
}
/*
*Displaying the details of the employees
*/
System.out.println("Acme Corporation\n");
System.out.println("Number of Employees: "+num);
System.out.println("Average Salary: "+String.format("%,.2f",Employee.averageSalary(employees,num)));
System.out.println("Annual Total: "+String.format("%,.2f",Employee.totalSalary(employees,num)));
System.out.println();
System.out.println("Name\t\tRank\tSalary");
for(Employee e : employees)
{
System.out.println(e.formatName()+"\t"+e.getRank()+"\t"+String.format("%,.2f", e.getSalary()));
}
}
}
employees.txt
Allie Gator A2 48000.00
Sally Mander A1 61123.89
Pete Zah A1 102468.20
Output Screenshot :
Program screenshots for indentation reference :