2011-12-04 72 views
3

我正在嘗試編寫一個程序,用於讀取每年從.txt文件中工作的小時數列表,分配/讀取(對正確的術語:)有一點模糊),它們放入一個數組,然後計算過量並打印它們。長期存儲百分比的問題

當我運行,控制檯輸出如下:

Employee 1 worked 1600 hours, an under-run of 160 or 0% 
Employee 3 worked 1680 hours, an under-run of 80 or 0% 

爲什麼百分比爲零?

import java.io.*; 
import javax.swing.*; 

class Calculator 
{ 
public static void main(String args[]) 
    { 

    try{ 

     String filePathString=JOptionPane.showInputDialog(null,"What is the file path?"); 

     FileInputStream fstream = new FileInputStream("C:\\hello.txt"); 
     BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
     String strLine; 
     int counter = 0; 
     long[] Array = new long[5]; 


     //Read File Line By Line 
     while (counter <= 4) 

     { 
      strLine = br.readLine(); 
      Array[counter] = Long.parseLong(strLine); 
      OverageUnderage(Array[counter], counter); 
      counter = counter + 1; 
     } 

    //Close the input stream 
    in.close(); 

    } 

    catch (Exception e){//Catch exception if any 
    System.err.println("Error: " + e.getMessage()); 
    } 
    } 

public static long OverageUnderage(long hours, long counter) 
{ 
long overageAmount = 0; 
long overagePercent = 0; 

    if (hours < 1760) 
    {  
     overageAmount = 1760 - hours; 
     overagePercent = ((overageAmount/1760)*100); 

     System.out.println("Employee "+counter+" worked "+hours+" hours, an under-run of "+overageAmount+" or "+overagePercent+"%"); 
    } 

    return counter; 
} 

} 

回答

6

數量(overageAmount/1760)被處理作爲一個長期的,而不是一個雙重的,你需要。嘗試:

overagePercent = ((overageAmount/1760.0) * 100); 

使用1760年的.0將它視爲一個十進制值。這將防止您看到的舍入爲0的問題,並允許計算在其餘計算中包含小數,從而爲您提供期望的結果。

3

這就是爲什麼(恕我直言)你把雙打改爲長:

overagePercent = ((overageAmount/1760)*100); 

這裏overageAmount/1760回報!
所以,你有兩種解決方案:

  1. 首先轉換overageAmount加倍,然後執行操作
  2. 鴻溝與浮動1760.0這樣造成數已經是一個浮動
1

您執行計算的順序很重要,尤其是對於int值。

而不是

overagePercent = overageAmount/1760 * 100; 

這很可能是0 * 100或0,你可以做

overagePercent = overageAmount * 100/1760; 

這可能仍然是0,但只有當答案是小於1

0

如果您需要以小數形式獲得答案,則必須使用雙精度或小數。 你不能使用整數的Long。