我有問題讓我的代碼總結了文本文件的所有工資。它應該把所有這些數字相加,並且給我平均薪水。此外,我遇到麻煩讓輸出中的一行正確格式化。請幫助,我對programmimg仍然很陌生!這是我的主要。printf和閱讀文本文件
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。謝謝!!
你讀的文件是怎麼看的?掃描儀的next()'讀取整行,可能不是你想要的 – Felk 2014-10-17 00:46:23
文本文件看起來就像輸出,只是沒有格式化。名字,等級和薪水之間只有空格。 – 2014-10-17 00:54:50
然後整個文件是1行,數據剛剛用空格分隔?然後你需要讀取一個字符串中的整個文件,並通過將其分割爲一個數組來存取這些部分:'String [] parts = string.split(「」);' – Felk 2014-10-17 00:57:03