首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >尝试在Java中添加数字时擦除txt文件中的数据

尝试在Java中添加数字时擦除txt文件中的数据
EN

Stack Overflow用户
提问于 2018-09-06 02:25:31
回答 1查看 59关注 0票数 0

下面的代码运行良好,除了将数字添加到现有的txt文件(Fred56.txt)的代码之外。他发布了:

代码语言:javascript
复制
PrintWriter outputfile = new PrintWriter(file);
outputfile.println(totalDeposit);
outputfile.close();

我试图搜索它,但当我问用户(扫描仪)文件名时,我找不到正确的答案。我想将totalDeposit添加到文件的现有数据中,而不是删除它们。

代码语言:javascript
复制
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);

    }

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-06 02:54:26

据我所知,您正在寻求一种以附加模式打开文件的解决方案。有几种方法可以实现这一点。您可以在代码中使用以下代码。

代码语言:javascript
复制
try{
   PrintWriter outputfile = new PrintWriter(new BufferedWriter(new FileWriter (filename, true)));
   outputfile.println(totalDeposit);
   outputfile.close();
   }catch(IOException ex){
// Handle your exception
   }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52191360

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档