在我的面向对象编程课程中,我有一项任务,要求我开发一个java代码,在使用.txt文件中的信息时打印出假公司的工资单信息。我能够打印出员工姓名和所有内容,但我在理解如何获得工资的平均值方面遇到一些麻烦,我已经开始采用这种方法,并在代码如下。任何帮助将不胜感激。
员工类:
public class Employee {
private String firstName;
private String lastName;
private String rank;
private double salary;
public Employee(String firstName, String lastName, String rank, double salary) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.rank = rank;
this.salary = salary;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
和
prog5 class:
import java.util.*;
import java.io.*;
public class Prog5 {
public static void main(String[] args) {
String firstName = null;
String lastName = null;
String rank = null;
double salary = 0.0;
Scanner inFile = null;
Employee[] arr = new Employee[99];
int num = 0;
try {
inFile = new Scanner( new File ( "c:\\Users\\admin\\workspace\\Shumaker5\\src\\employees.txt"));
}
catch(FileNotFoundException e) {
System.err.println(" File not found");
System.exit(1);
}
//read file
while(inFile.hasNext()) {
try {
firstName = inFile.next();
lastName = inFile.next();
rank = inFile.next();
salary = inFile.nextDouble();
}
catch(InputMismatchException e) {
System.err.println("File format error");
System.exit(1);
}
Employee emp = new Employee(firstName, lastName, rank, salary);
arr[num] = emp;
num++;
/**
* method to calculate average
* @param temperatures
* @param counter
* @return
*/
/** public static double average( double[] salary, int num )
{
double sum = 0;
for( int t = 0; t < num; t++)
{
sum += salary[t];
}
return (double) sum / num;
} */
System.out.println(emp);
}
System.out.println();
System.out.println("Wayne Industries");
System.out.println();
System.out.println("Number of Employees: " + num);
System.out.println("Average Salary: ");
System.out.println("Annual Total: ");
System.out.println();
System.out.printf("%-15s %-15s %-6s %-8s \n", "Last Name", "First Name", "Rank", "Salary");
System.out.println();
for(int x = 0; x < num; x++) {
System.out.printf("%-15s %-15s %-6s %-8.2f\n", arr[x].getLastName(),
arr[x].getFirstName(), arr[x].getRank(), arr[x].getSalary());
}
inFile.close();
}
}
答案 0 :(得分:0)
我怀疑你需要首先以字符串的形式检索薪水,然后提取双倍(例如使用Double.parseDouble(薪水))。希望这有帮助!
答案 1 :(得分:0)
你非常接近。我们只需要传递一系列员工(而不是他们的工资)并计算方法中的平均值。下面提供了一个示例:
public static double average( Employee[] employees ){
double sum = 0;
for( int t = 0; t < employees.length; t++){
sum += employee[t].getSalary();
}
return (double) sum / employees.length;
}