貯蓄を追跡できる簡単なプログラムを作成しています。週番号、収入、および保存されたフィールドを含めました。このデータをテキスト ファイルに保存してから、テキスト領域に取得できます。プログラムを閉じてから再度実行するときに、実行中の合計「合計」を追跡するにはどうすればよいですか。実行中の合計として配列を使用しましたが、配列を強制終了してから再度開くと、これが最初からやり直されます (明らかに)。
これが保存と読み取りのための私のコードです。要約すると、最後のフィールド「合計」を変数として取得して、新しい入力に追加できるようにしたいと考えています。
//get week and validate:
strWeek = txtWeek.getText();
if (strWeek.isEmpty())
{
JOptionPane.showMessageDialog(null, "Enter Week Number");
return;
}
else
week = Integer.parseInt(strWeek);
//get income and validate:
strIncome = txtIncome.getText();
if (strIncome.isEmpty())
{
JOptionPane.showMessageDialog(null, "Enter Income");
return;
}
else
income = Double.parseDouble(strIncome);
//get saved:
strSaved = txtSaved.getText();
if (strSaved.isEmpty())
{
JOptionPane.showMessageDialog(null, "Enter Saved");
return;
}
else
saved = Double.parseDouble(strSaved);
total = total + saved;
txtOutput.append(week + "\t" + income + "\t" + saved + "\t" + total + "\n");
txtWeek.setText(null);
txtIncome.setText(null);
txtSaved.setText(null);
try
{
File output = new File("C:\\savingsApp/Savings.txt");
BufferedWriter outFile = new BufferedWriter (new FileWriter(output.getPath(), true));
outFile.write(week + "\t" + income + "\t" + saved + "\t" + total);
outFile.newLine();
outFile.close();
JOptionPane.showMessageDialog(null, "Savings updated");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "IO file error");
}
txtOutput.setText(null);
//Declare:
String incomingString = "";
int counter = 0;
//get file:
try
{
File inputFile = new File ("C:\\savingsApp/savings.txt");
BufferedReader inFile = new BufferedReader (new FileReader(inputFile));
incomingString = inFile.readLine();
while (incomingString != null)
{
counter++;
txtOutput.append(incomingString + "\n");
incomingString = inFile.readLine();
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "error loading file");
}