1

I am asked to make a bank account java program. I have made it and the values in the regular print works, but when I use print stream for the text file, half of the values have been changed, but the other half have not been changed to two decimal places. The current code is below. If you want the code with comments it is inside of the googledrive link attached.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;

public class Bank {

    public static void main(String[] args) throws FileNotFoundException {
        final int maxAccounts = 10;
        String[] accountNumbers = new String[maxAccounts];
        double[] balances = new double[maxAccounts];

        final String FILENAME = "accounts.txt";
        Scanner sc = new Scanner(System.in);
        Scanner fileScanner = new Scanner(new File(FILENAME));

        int numAccounts = readAccounts(accountNumbers, balances, fileScanner);

        char choice;
        // Set up the menu
        do {
            printMenu();
            choice = sc.next().charAt(0);
            switch (choice) {
                case 'b':
                    getBalance(accountNumbers, balances, numAccounts, sc);
                    break;
                case 'd':
                    makeDeposit(accountNumbers, balances, numAccounts, sc);
                    break;
                case 'w':
                    makeWithdrawal(accountNumbers, balances, numAccounts, sc);
                    break;
                case 'a':
                    boolean added = addAccount(accountNumbers, balances, numAccounts, maxAccounts, sc);
                    if (added) {
                        numAccounts++;
                    }
                    break;
                case 'p':
                    printAccounts(accountNumbers, balances, numAccounts);
                    break;
                case 'q':
                    break;
                default:
                    System.out.println("Invalid choice; try again.");
            }
        } while (choice != 'q');
        
        // printAccounts(accountNumbers, balances, numAccounts);
        printAccounts(accountNumbers, balances, numAccounts, FILENAME);
    }


     
    public static int readAccounts(String[] accountNumbers, double[] balances, Scanner sc) {
        // TODO
        int numAccounts = 0;
        while (sc.hasNext()) {
            String accountNumber = sc.next();
            double balance = sc.nextDouble();
            accountNumbers[numAccounts] = accountNumber;
            balances[numAccounts] = balance;
            numAccounts++;
        }

        return numAccounts;
    }


    public static void printMenu() {
        System.out.println("\nChoices:");
        System.out.println("b: get balance");
        System.out.println("d: make deposit");
        System.out.println("w: make withdrawal");
        System.out.println("a: add account");
        System.out.println("p: print accounts to screen");
        System.out.println("q: quit");
        System.out.print("Enter a letter choice: ");
    }


    public static int indexOfAccount(String[] accountNumbers, String accountNumber, int numAccounts) {
        // TODO
        for (int i = 0; i < numAccounts; i++) {
            if (accountNumbers[i].equals(accountNumber)) {
                return i;
            }
        }
        return -1;

    }

    public static void getBalance(String[] accountNumbers, double[] balances, int numAccounts, Scanner sc) {

        System.out.print("account number: ");
        String accountNumber = sc.next();

        int index = indexOfAccount(accountNumbers, accountNumber, numAccounts);

        if (index == -1) {
            System.out.println("Sorry, that account doesn't exist.");
        } else {
            double balanceRounded = round(balances[index]);
            System.out.printf("The balance is $" +"%.2f\n", balanceRounded);
        }

    }


    public static void makeDeposit(String[] accountNumbers, double[] balances, int numAccounts, Scanner sc) {

        System.out.print("account number: ");
        String accountNumber = sc.next();
        int index = indexOfAccount(accountNumbers, accountNumber, numAccounts);
        if (index == -1) {
            System.out.println("Sorry, that account doesn't exist.");
        } else {
            System.out.print("amount to deposit: ");
            double deposit = sc.nextDouble();
            System.out.print("Deposit successful.\n");
            balances[index] = balances[index] + deposit;

        }

    }

    public static void makeWithdrawal(String[] accountNumbers, double[] balances, int numAccounts, Scanner sc) {
        System.out.print("account number: ");
        String accountNumber = sc.next();
        int index = indexOfAccount(accountNumbers, accountNumber, numAccounts);
        if (index == -1) {
            System.out.println("Sorry, that account doesn't exist.");
        } else {
            System.out.print("amount to withdraw: ");
            double withdrawl = sc.nextDouble();
            balances[index] = balances[index] - withdrawl;
            System.out.print("Withdrawal successful.\n");
        }
    }


    public static boolean addAccount(String[] accountNumbers, double[] balances, int numAccounts, int maxAccounts,
            Scanner sc) {
        if (numAccounts >= maxAccounts) {
            System.out.println("Sorry, the database is full.");
            return false;
        }

        System.out.print("new account number (six digits): ");
        String accountNumber = sc.next();
        int numDigits = String.valueOf(accountNumber).length();
        if (numDigits != 6) {
            System.out.println("Sorry, account number must be exactly six digits.");
            return false;
        }
        int index = indexOfAccount(accountNumbers, accountNumber, numAccounts);
        if (index != -1) {
            System.out.println("Sorry, that account already exists.");
            return false;
        }
        accountNumbers[numAccounts] = accountNumber;
        balances[numAccounts] = 0.00;
        System.out.println("Account added.");

        return true;
    }


    public static void printAccounts(String[] accountNumbers, double[] balances, int numAccounts) {
        for (int i = 0; i < numAccounts; i++) {
            double balanceRounded = round(balances[i]);
            System.out.printf(accountNumbers[i] + " " + "%.2f\n", balanceRounded);
        }
    }


    public static void printAccounts(String[] accountNumbers, double[] balances, int numAccounts,
            String filename) throws FileNotFoundException {
        PrintStream ps = new PrintStream(filename);
        
        for (int i = 0; i < numAccounts; i++) {
            double balanceRounded = round(balances[i]);
            ps.print(accountNumbers[i] + " " +  balanceRounded + "\n" );
            
        }
        ps.close();

    }
    public static final DecimalFormat df = new DecimalFormat("0.00");
    public static double round(double a)
    {
        double balanceRounded = Math.round(a * 100.00) / 100.00;
        double val1 = balanceRounded;
        BigDecimal bd = new BigDecimal(val1).setScale(2, RoundingMode.HALF_UP);
        double val2 = bd.doubleValue();
        return val2;      
    }
}

The text file is named accounts.txt and the original values are:

460782 124.0
088619 2812.0
790643 4375.85
874951 45675.0
492468 86.58
474800 52424.86
848769 46.56
681837 29.79

But once I run the program and doing some operations I get this in the text file, which is different from how it appears in the console. Here is the link for the files: https://drive.google.com/drive/folders/1aDpOD0aG7wrQRGLB14sajbcQxmeaRUjj?usp=sharing

It contains the account.txt, bank.java, and what I inputted into the console to get this result.

I have tried a couple of methods before. I have tried to use formatting, but when I use printf() it doesn't work at all for some reason. Then I have also tried to divide the printing of the two arrays into two different print statements, but that also has not worked.

460782 124.0
088619 2812.0
790643 4375.85
874951 45675.0
492468 86.58
474800 52424.86
848769 46.56
681837 29.79
111111 0.0
222222 0.0
Slaw
  • 37,820
  • 8
  • 53
  • 80
Aortax
  • 23
  • 6
  • 1
    You have two different `printAccounts` methods, one for printing to standard output and one for printing to a file, and they format the data two different ways. One uses printf with a `%.2f` format specifier and the other uses plain string concatenation. (Also, you shouldn't be using `double` for monetary values.) – David Conrad Jun 09 '22 at 22:26
  • `ps.print(accountNumbers[i] + " " + balanceRounded + "\n" );` doesn't format to 2 decimal place. – Mark Rotteveel Jun 10 '22 at 10:28

1 Answers1

0

Changing the readAccounts method to this has worked in my case verry well.

 public static int readAccounts(String[] accountNumbers, double[] balances, Scanner sc) {
    // TODO
    int numAccounts = 0;
    while (sc.hasNext()) {
        String line = sc.nextLine();
        String accountNumber = line.split(" ")[0];
        double balance = Double.parseDouble(line.split(" ")[1]);
        accountNumbers[numAccounts] = accountNumber;
        balances[numAccounts] = balance;
        numAccounts++;
    }

    return numAccounts;
}

Console output:

Enter a letter choice: p
460782 124,00
088619 2812,00
790643 4375,85
874951 45675,00
492468 86,58
474800 52424,86
848769 46,56
681837 29,79

Even make a new Account 123456 adding 11,6 removing 1 gives following output:

460782 124,00
088619 2812,00
790643 4375,85
874951 45675,00
492468 86,58
474800 52424,86
848769 46,56
681837 29,79
*123456 10,60*

The Account works fine now.

BTW, i added my bankaccount 1000$

EDIT

Also edited the round method in your Class to returns a String, because evrytime you want to round you print the value of Double. If a Double is rounded to as an example 12.50 the last Zero will be cut off. In a String not.

public static String round(double a)
{
    DecimalFormat df = new DecimalFormat("0.00");
    df.setRoundingMode(RoundingMode.FLOOR);
    String balanceRounded = df.format(a);
    return balanceRounded.replace(",",".");
}

Because of changeing this method i had to change the print methods:

public static void printAccountsToScreen(String[] accountNumbers, double[] balances, int numAccounts) {
        for (int i = 0; i < numAccounts; i++) {

            System.out.println(accountNumbers[i] +" " +round(balances[i]));
        }
    }


    public static void printAccountsToFile(String[] accountNumbers, double[] balances, int numAccounts,
                                           String filename) throws FileNotFoundException {
        PrintStream ps = new PrintStream(filename);

        for (int i = 0; i < numAccounts; i++) {
            ps.print(accountNumbers[i] + " " +  round(balances[i]) + "\n" );

        }
        ps.close();

    }

After adding account 123456 and make some withdrawls and deposits the accounts.txt looks:

460782 124.00
088619 2812.00
790643 4375.85
874951 45675.00
492468 86.58
474800 52424.86
848769 46.56
681837 29.79
123456 26.65