【发布时间】:2016-04-13 01:39:54
【问题描述】:
我打开了一个文件,打印出来很好,看起来有点像这样;
约翰霍普 13 12.00
劳拉小屋 6 15.00
但是数组是 6。由于我有另一个带有 getter 和 setter 的类,因此该文件能够获取每个人的总工资:
约翰 13 12.00 150.00
劳拉小屋 6 15.00 120.00
我想打印所有个人的总工资,然后得到平均值。 这是我的一些代码
public class PayRoll {
public static void main(String[] args) {
final int NUMBER_OF_WORKERS = 15;
final String INPUT_FILE = "data.txt";
Worker[] worker_ar = new Worker[NUMBER_OF_WORKERS];
Scanner file = null;
try {
file = new Scanner(new File(INPUT_FILE));
} catch (FileNotFoundException e) {
System.err.println("File Not Found!");
}
String line = null;
int count = 0;
double total_pay = 0;
double avg_pay = 0;
while ((file.hasNextLine()) && (count < worker_ar.length)) {
String fName = file.next();
String lName = file.next();
int hours = file.nextInt();
double hrly_pay = file.nextDouble();
worker_ar[count] = new Worker(fName, lName, hours, hrly_pay);
count++;
//Here, i tried computing the average but it is wrong.
for (int i = 0; i < count; i++)
total_pay = total_pay + worker_ar[i].computePay();
avg_pay = total_pay / count;
【问题讨论】:
-
您不需要在 while 循环中使用
for()循环。把它放在while循环运行之后,你把所有的工资加到total_pay并除以count。编辑:就像艾略特提交的答案一样。
标签: java arrays file class methods