2016-04-13 110 views
-1

我打開了一個文件,打印出來很好,看起來有點像這樣;我可以幫助計算平均值和總值嗎?

約翰合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; 
+0

你不需要在while循環中有'for()'循環。在'while'循環運行之後放置它,你將所有工資總和到'total_pay'中,並用'count'除。編輯:就像艾略特提交的答案一樣。 – Norsk

回答

1

讀完計算總平均(或至少平均)之前。類似於

double total_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); 
    total_pay += worker_ar[count].computePay(); // <-- add this worker's 
               //  pay to the total. 
    count++; 
} 
double avg_pay = total_pay/count; // <-- calculate the average when 
            //  there is a total. 
+0

非常感謝。有效。這些小細節可以真正影響程序。再次感謝。 –