【发布时间】:2018-09-05 18:25:30
【问题描述】:
以下代码工作正常,除了应该将数字添加到现有 txt 文件 (Fred56.txt) 的代码。他发布了:
PrintWriter outputfile = new PrintWriter(file);
outputfile.println(totalDeposit);
outputfile.close();
我尝试搜索它,但在询问用户(扫描仪)文件名时找不到正确答案。我想将totalDeposit 添加到文件中的现有数据中,但不删除它们。
import java.io.*;
import java.util.Scanner;
public class TestSavingsAccount {
public static void main(String[] args) throws IOException {
double totalDeposit = 0;
double totalInterest = 0 ;
double totalWithdraw = 0;
String filename ;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the annual interest rate");
double userAnnualinterest = keyboard.nextDouble();
System.out.println(" Enter the starting balance");
double userStartingbalance = keyboard.nextDouble();
System.out.println(" Enter the number of months");
int userNumberMonths = keyboard.nextInt();
SavingsAccount account1 = new SavingsAccount(userStartingbalance);
account1.setAnnualInterest(userAnnualinterest);
for(int currentmonth = 1 ; currentmonth <= userNumberMonths; currentmonth ++ )
{
System.out.println("How much did you deposit during the month ?" + currentmonth);
double depositAmount = keyboard.nextDouble();
account1.deposit(depositAmount);
totalDeposit += depositAmount ;
System.out.println("How much do you want to withdraw ?" + currentmonth);
double userWithdraw = keyboard.nextDouble();
account1.withdraw(userWithdraw);
totalWithdraw += userWithdraw ;
totalInterest += account1.addMonthlyInterest();
keyboard.nextLine() ;
System.out.println(" What is the file name ?");
filename = keyboard.nextLine() ;
File file = new File(filename);
PrintWriter outputfile = new PrintWriter(file);
outputfile.println(totalDeposit);
outputfile.close();
}
System.out.println(" The final balance of the end " + userNumberMonths + "is" +
account1.getBalance() + " total amount of withdraw " + totalWithdraw +
" Total amount of deposit " +totalDeposit + " The total of interest" + totalInterest);
}
}
【问题讨论】:
-
我这样做了,但它仍然会擦除以前的数据。 { 键盘.nextLine() ; System.out.println("文件名是什么?");文件名 = 键盘.nextLine() ;文件文件 = 新文件(文件名); PrintWriter outputfile = new PrintWriter(file); outputfile.println(totalDeposit);输出文件.close(); }
标签: java file file-writing