我正在制作一个简单的程序,我可以在其中跟踪我的储蓄。我已经包括了周数、收入和保存的字段。我将此数据保存到文本文件中,然后可以将其检索到文本区域。关闭程序然后再次运行它时,如何跟踪我的运行总数“总数”。我使用了一个数组作为运行总计,但是当我杀死它然后重新打开它(显然)时,这会重新开始。
这是我的保存和阅读代码。总而言之,我希望能够将最后一个字段“总计”作为变量检索,以便可以将其添加到新输入中。
//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");
}