我在让代码总结文本文件的所有工资时遇到了问题。它应该总结所有这些,并给我一个平均工资。此外,我在输出中的其中一行正确格式化时遇到了麻烦。请帮助,我仍然是programmimg的新手!这是我的主要内容。
import java.util.*;
import java.io.*;
public class fileIn
{
public static void main(String[] args)
{
String fName;
String lName;
String rank;
double salary = 0;
double newSal = 0;
Scanner inFile = null;
Employee[] emp = new Employee[20];
int numEmployee = 0;
// open the file
try
{
inFile = new Scanner(new File("employee.txt"));
} catch (FileNotFoundException e)
{
System.err.println("Error: File employee.txt not found ");
}
while (inFile.hasNext())
{
fName = inFile.next();
lName = inFile.next();
rank = inFile.next();
newSal = inFile.nextDouble();
salary += newSal;
emp[numEmployee] = new Employee(fName, lName, rank, salary);
numEmployee++;
}
System.out.println("Acme Corporation \n");
System.out.printf("Number Of Employees: %5d ", numEmployee);
System.out.printf("\nAverage Salary: %13.2f", salary / numEmployee);
System.out.printf("\nAnnual Total %16.2f", salary );
System.out.printf("\n\n%-8s %15s %10s", "Name", "Rank", "Salary\n");
for (int i = 0; i < numEmployee; i++)
{
System.out.printf("%s, %s \t%7s %11.2f\n", emp[i].getlName(),
emp[i].getfName(), emp[i].getRank(), emp[i].getSalary());
}
inFile.close();
}
}
这是一个示例输出:
Acme Corporation
Number Of Employees: 9
Average Salary: 58740.50
Annual Total 528664.54
Name Rank Salary
------------------ ---- ---------
Jones, William B2 42500.00
Baker, Susan A3 107500.00
Caine, Horatio A1 191268.95
Baer, Teddy B4 244268.95
Gator, Allie A2 292268.95
Mander, Sally A1 354392.84
Aspargus, Amy A1 454442.84
Huckleberry, Henry B1 495677.34
Rutabaga, Ryan B2 528664.54
平均工资和年度总数完全错误,总数应该超过200万,平均工资应该是大约300k。谢谢!!
答案 0 :(得分:0)
看起来您正在为每个新员工输入分配累积薪水:
emp[numEmployee] = new Employee(fName, lName, rank, salary);
不应该这样吗?
emp[numEmployee] = new Employee(fName, lName, rank, newSal);