[英]java: loop produces incorrect output when reading from file?
此循環生成小時和支付金額的平均值,但輸出在數學上不正確。 如何編輯此代碼以生成正確的平均小時值和平均付費值?
Scanner openFile = new Scanner(inFile);
while (openFile.hasNext()) {
if (openFile.hasNextDouble()) {
totalHours += openFile.nextDouble();
numOfHourInputs++;
}
if (openFile.hasNextDouble()) {
totalPaid += openFile.nextDouble();
numOfCharges++;
}
else {
openFile.next(); }
}
averageHours = (totalHours/numOfHourInputs);
averagePaid = (totalPaid/numOfCharges);
以下是我的文件:第一列對於計算平均值並不重要。 第二列包含小時數。 第三欄包含費用。
該文件可以為用戶添加更多數據 - 可以更改文件內部的值。 a 10.0 9.95 b 10.0 13.95 b 20.0 13.95 c 50.0 19.95 c 30.0 19.95
刪除其他:
else {
openFile.next(); //this consumes all input
}
以下代碼
Double[][] values = {{10.0, 9.95},
{10.0, 13.95},
{20.0, 13.95},
{50.0, 19.95},
{30.0, 19.95}};
Double totalHours = 0.;
int numOfHourInputs = 0;
Double totalPaid = 0.;
int numOfCharges = 0;
for (final Double[] value : values) {
totalHours += value[0];
numOfHourInputs++;
totalPaid += value[1];
numOfCharges++;
}
final double averageHours = (totalHours / numOfHourInputs);
System.out.println("averageHours = " + averageHours);
final double averagePaid = (totalPaid / numOfCharges);
System.out.println("averagePaid = " + averagePaid);
產生了結果
averageHours = 24.0
averagePaid = 15.55
所以這顯然不是一個數學問題。 檢查輸入代碼,尤其是線路
openFile.next();
你仍然需要跳過第一個令牌但是在正確的位置:
public static void main(String[] args)
{
double totalHours = 0.0;
int numOfHourInputs = 0;
double totalPaid = 0.0;
int numOfCharges = 0;
Scanner openFile = null;
try
{
openFile = new Scanner(new File("c:\\temp\\pay.txt"));
}
catch (Exception e)
{
throw new RuntimeException("FNF");
}
try
{
while (openFile.hasNext())
{
// skip the first token
String token = openFile.next();
if (openFile.hasNextDouble())
{
totalHours += openFile.nextDouble();
numOfHourInputs++;
}
if (openFile.hasNextDouble())
{
totalPaid += openFile.nextDouble();
numOfCharges++;
}
}
}
finally
{
openFile.close();
}
double averageHours = (totalHours/numOfHourInputs);
double averagePaid = (totalPaid/numOfCharges);
System.out.println("Total hours: " + totalHours);
System.out.println("Num hours input: " + numOfHourInputs);
System.out.println("----------------------------------------");
System.out.println("Average hours: " + averageHours);
System.out.println("");
System.out.println("Total payments: " + totalPaid);
System.out.println("Num payments input: " + numOfCharges);
System.out.println("----------------------------------------");
System.out.println("Average paid: " + averagePaid);
}
這是我得到的輸出:
Total hours: 120.0
Num hours input: 5
----------------------------------------
Average hours: 24.0
Total payments: 77.75
Num payments input: 5
----------------------------------------
Average paid: 15.55
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.