how to ask the user to enter account number and then return his balance from a text file [closed]

I have a text file that has two columns, one for account numbers and the other for balances. I would like to ask the user for his account number and get his balance from the text. I have methods like deposit and withdraw, which I want to apply to the balances of the user, and then update the text file. What is the best way to do it? Should I use an array? or there are easier ways to do?

The text file would be like this

1001 50.67
1002 500.32
1003 63.63
1004 953.53
1005 735.22

Answer

Using an array is not a practical approach to this problem. I made a sample program that does the above without an array. To make this run, make sure your account file is names BankAccounts.txt

import java.io.*;
import java.util.*;

public class BankAccount {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        File dir = new File("BankAccounts.txt");
        System.out.println("Please enter your bank account number.");
        String bankNumber = input.nextLine();
        input.close();
        System.out.println("Your Balance is: "
                + balanceFromAccount(bankNumber, dir));
    }

    public static String balanceFromAccount(String accountNumber, File file) {
        String tempNumber = "";
        int i;
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));

            String line = null;
            while ((line = br.readLine()) != null) {
                for (i = 0; line.charAt(i) != ' '; i++) {
                    tempNumber = tempNumber.concat(line.substring(i, i + 1));
                }
                if (tempNumber.equals(accountNumber)) {
                    return line.substring(i + 1);
                }
                tempNumber = "";
            }
            br.close();
        } catch (Exception e) {

        }
        return "Not Found!";

    }

}

This program simply opens the file, finds each bank account number, checks if it is the desired one, then it returns the value if it is. If not, it says “Not Found!”

Leave a Reply

Your email address will not be published. Required fields are marked *