嗨,我是一名AP計算機科學專業的學生,這看起來像是一個愚蠢的問題,但請與我同行。如何更新for循環中更改的變量?
這是作業
程序說明:你剛開始工作作爲一名程序員。您已同意以下薪酬方案。
•您每小時支付30美元。 •在工作時間超過8小時的任何一天中,您每小時可以多掙25.5美元。
•在任何一週內,您可以獲得額外的每小時15美元,超過40美元的時間。
•您在星期六工作時賺取的任何獎金都可獲得125%的獎金,並在星期天工作時獲得50%的獎金。
工作時間,我用,存儲爲TXT文件閱讀器
9 8 10 8 9 9 5 7 8 8 8 0 8 9 6 10 5 0 0 0 0 8 8 8 8 8 8 8 6 6 6 6 6 6 6 10 3 4 5 7 5 4 8 8 8 8 8 0 0
樣本輸出:(務必通過添加額外的數據傳輸到數據文件來運行自己的多組測試)
Hours Worked: 9 8 10 8 9 9 5 Week # 1 $2581.88 Hours Worked: 7 8 8 8 0 8 9 Week # 2 $2033.25 Hours Worked: 6 10 5 0 0 0 0 Week # 3 $681 Hours Worked: End of reading from file. Vs My output Total Hours Worked: 58 Week #1 $2010.00 Total Hours Worked: 48 Week #2 $1560.00 Total Hours Worked: 21 Week #3 $630.00 Total Hours Worked: 56 Week #4 $1920.00 Total Hours Worked: 42 Week #5 $1290.00 Total Hours Worked: 38 Week #6 $1140.00 Total Hours Worked: 40 Week #7 $1200.00 Hours Worked: End of reading from file.
我看到的問題是,for循環內發生的事情不會影響我的代碼的外部,我發現令人困惑。
請不要更改整個代碼,我也想了解我當前的代碼,以便我可以學習和進步,謝謝!
import java.util.*;
import java.io.*;
import java.text.*;
public class wages {
public static void main(String[] args) {
Scanner inFile = null;
int TotalW = 0; // total hours per week
int TotalD = 0; // total hours per day
double Wage = 0.0; // Wage for the weekdays
double WageS = 0.0; // wage for sat
double WageSu = 0.0; // wage for Sundays
double Total = Wage + WageS + WageSu;
int week = 1; // week # counter
DecimalFormat TD = new DecimalFormat("0.00"); // formatter
try {
// Create a scanner to read the file, file name is parameter
inFile = new Scanner(new File("Prog213a.txt"));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
// Stop program if no file found
System.exit(0);
}
while (inFile.hasNext()) // as long as there is a next variable...
{
for (int x = 1; x <= 5; x++) // count the week days/first 5 variables
{
TotalD = inFile.nextInt();
if (TotalD > 8) Wage = Wage + ((TotalD - 8) * 25.50); // bonus if worked above 8 hours per day
TotalW = TotalW + TotalD;
}
for (int x = 1; x <= 1; x++) {
TotalD = inFile.nextInt();
if (TotalD > 8) WageS = WageS + ((TotalD - 8) * 25.50);
WageS = WageS + (WageS * 2.25);
TotalW = TotalW + TotalD;
}
for (int x = 1; x <= 1; x++) {
TotalD = inFile.nextInt();
if (TotalD > 8) WageSu = WageSu + ((TotalD - 8) * 25.50);
WageSu = WageSu + (WageSu * 2);
TotalW = TotalW + TotalD;
}
if (TotalW > 40) Total = Total + ((TotalW - 40) * 15);
Total = Total + (TotalW * 30);
System.out.println("Total Hours Worked: " + TotalW);
System.out.println("Week #" + (week++) + " $" + TD.format(Total));
TotalW = 0;
TotalD = 0;
Wage = 0;
WageS = 0;
WageSu = 0;
Total = Wage + WageS + WageSu;
}
System.out.println("Hours Worked: End of reading from file. ");
}
}
您需要了解示波器。從這裏開始:http://www.java-made-easy.com/variable-scope.html –
我當然會感謝你! – Basam