Стирание моих данных в текстовом файле при попытке добавить числа в Java - PullRequest
0 голосов
/ 05 сентября 2018

Следующий код работает нормально, за исключением кода, который должен добавлять числа в существующий текстовый файл (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);

    }

}

1 Ответ

0 голосов
/ 05 сентября 2018

Насколько я понимаю, вы просите решение открыть файл в режиме добавления. Есть несколько способов достичь этого. Вы можете использовать следующее в коде.

try{
   PrintWriter outputfile = new PrintWriter(new BufferedWriter(new FileWriter (filename, true)));
   outputfile.println(totalDeposit);
   outputfile.close();
   }catch(IOException ex){
// Handle your exception
   }
...