JavaRush /Java Blog /Random EN /Coffee break #201. How to create a console banking applic...

Coffee break #201. How to create a console banking application in Java

Published in the Random EN group
Source: Medium Today we will develop a simple Java application for a banking system. It will help us better understand how OOP concepts are used in Java programs. Coffee break #201.  How to create a console banking application in Java - 1To begin with, we will need a Java environment installed on the computer, preferably Java 11. Next, we will start with a detailed description of the functions of the console application. Functional:
  1. Create an account;
  2. Enter exit;
  3. Display of the last 5 transactions;
  4. Cash deposit;
  5. Display current user information.
Object-oriented programming concepts used:
  1. Inheritance;
  2. Polymorphism;
  3. Encapsulation.

Application development

Let's create a new Java project in Eclipse or IntelliJ IDEA. Let's define a new interface called SavingsAccount .
public interface SavingsAccount {

    void deposit(double amount, Date date);
}
I have implemented an interface that hosts the deposit method . I call this method every time I add money to my checking account. The OOP concept used here is polymorphism (methods in an interface do not have a body). The implementation of this method can be found in the Customer class by overriding a method with the same name and parameters. This way you override a method from the parent interface in the child class. Then we need a client to add money to the checking account. But first, let's define our Customer class .
public class Customer extends Person implements SavingsAccount {

    private String username;

    private String password;

    private double balance;

    private ArrayList<String> transactions = new ArrayList<>(5);

    public Customer(String firstName, String lastName, String address, String phone, String username, String password, double balance, ArrayList<String> transactions, Date date) {
        super(firstName, lastName, address, phone);
        this.username = username;
        this.password = password;
        this.balance = balance;
        addTransaction(String.format("Initial deposit - " + NumberFormat.getCurrencyInstance().format(balance) + " as on " + "%1$tD" + " at " + "%1$tT.", date));
    }

    private void addTransaction(String message) {

        transactions.add(0, message);
        if (transactions.size() > 5) {
            transactions.remove(5);
            transactions.trimToSize();
        }
    }

//Getter Setter

    public ArrayList<String> getTransactions() {
        return transactions;
    }

    @Override
    public void deposit(double amount, Date date) {

        balance += amount;
        addTransaction(String.format(NumberFormat.getCurrencyInstance().format(amount) + " credited to your account. Balance - " + NumberFormat.getCurrencyInstance().format(balance) + " as on " + "%1$tD" + " at " + "%1$tT.", date));
    }

    @Override
    public String toString() {
        return "Customer{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", balance=" + balance +
                ", transactions=" + transactions +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Customer customer = (Customer) o;

        if (Double.compare(customer.getBalance(), getBalance()) != 0) return false;
        if (getUsername() != null ? !getUsername().equals(customer.getUsername()) : customer.getUsername() != null)
            return false;
        if (getPassword() != null ? !getPassword().equals(customer.getPassword()) : customer.getPassword() != null)
            return false;
        return getTransactions() != null ? getTransactions().equals(customer.getTransactions()) : customer.getTransactions() == null;
    }

    @Override
    public int hashCode() {
        int result;
        long temp;
        result = getUsername() != null ? getUsername().hashCode() : 0;
        result = 31 * result + (getPassword() != null ? getPassword().hashCode() : 0);
        temp = Double.doubleToLongBits(getBalance());
        result = 31 * result + (int) (temp ^ (temp >>> 32));
        result = 31 * result + (getTransactions() != null ? getTransactions().hashCode() : 0);
        return result;
    }
The OOP concept used here is inheritance , as the Customer class receives properties from the Person class . That is, almost all attributes of the Person class are inherited and parent-child relationships are visible from Person to Customer . Now we need a constructor with all the attributes of the two classes and adding a superconstructor keyword to specify the inherited attributes. When implementing the SavingsAccount interface , we must override the deposit method in the Customer class . To do this, we will write an implementation of the method in this class. Additionally, the transaction list is initialized to display the last five transactions. The constructor calls the addTransaction method , which displays the date of changes and completed transactions.
private void addTransaction(String message) {

        transactions.add(0, message);
        if (transactions.size() > 5) {
            transactions.remove(5);
            transactions.trimToSize();
        }
    }
Now let's talk about the parent class Person .
public class Person {

    private String firstName;

    private String lastName;

    private String address;

    private String phone;

    public Person() {}

    public Person(String firstName, String lastName, String address, String phone) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
        this.phone = phone;
    }

//Getters Setters

 @Override
    public String toString() {
        return "Person{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", address='" + address + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }

@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;

        if (getFirstName() != null ? !getFirstName().equals(person.getFirstName()) : person.getFirstName() != null)
            return false;
        if (getLastName() != null ? !getLastName().equals(person.getLastName()) : person.getLastName() != null)
            return false;
        if (getAddress() != null ? !getAddress().equals(person.getAddress()) : person.getAddress() != null)
            return false;
        return getPhone() != null ? getPhone().equals(person.getPhone()) : person.getPhone() == null;
    }

    @Override
    public int hashCode() {
        int result = getFirstName() != null ? getFirstName().hashCode() : 0;
        result = 31 * result + (getLastName() != null ? getLastName().hashCode() : 0);
        result = 31 * result + (getAddress() != null ? getAddress().hashCode() : 0);
        result = 31 * result + (getPhone() != null ? getPhone().hashCode() : 0);
        return result;
    }
In the Person class, we used the concept of encapsulation by applying the private access modifier to each attribute. Encapsulation in Java can be defined as the mechanism by which methods that operate on this data are combined into a single unit. Essentially, data from the Person class is only available in this class, and not in other classes or packages. And finally, our main class, called Bank . This is the main class from where we run the application and interact with the functionality of all classes.
public class Bank {

    private static double amount = 0;
    Map<String, Customer> customerMap;

    Bank() {
        customerMap = new HashMap<String, Customer>();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        Customer customer;
        Bank bank = new Bank();
        int choice;
        outer:
        while (true) {

            System.out.println("\n-------------------");
            System.out.println("BANK    OF     JAVA");
            System.out.println("-------------------\n");
            System.out.println("1. Registrar cont.");
            System.out.println("2. Login.");
            System.out.println("3. Exit.");
            System.out.print("\nEnter your choice : ");
            choice = sc.nextInt();
            sc.nextLine();
            switch (choice) {
                case 1:
                    System.out.print("Enter First Name : ");
                    String firstName = sc.nextLine();
                    System.out.print("Enter Last Name : ");
                    String lastName = sc.nextLine();
                    System.out.print("Enter Address : ");
                    String address = sc.nextLine();
                    System.out.print("Enter contact number : ");
                    String phone = sc.nextLine();
                    System.out.println("Set Username : ");
                    String username = sc.next();
                    while (bank.customerMap.containsKey(username)) {
                        System.out.println("Username already exists. Set again : ");
                        username = sc.next();
                    }
                    System.out.println("Set a password:");
                    String password = sc.next();
                    sc.nextLine();

                    customer = new Customer(firstName, lastName, address, phone, username, password, new Date());
                    bank.customerMap.put(username, customer);
                    break;

                case 2:
                    System.out.println("Enter username : ");
                    username = sc.next();
                    sc.nextLine();
                    System.out.println("Enter password : ");
                    password = sc.next();
                    sc.nextLine();
                    if (bank.customerMap.containsKey(username)) {
                        customer = bank.customerMap.get(username);
                        if (customer.getPassword().equals(password)) {
                            while (true) {
                                System.out.println("\n-------------------");
                                System.out.println("W  E  L  C  O  M  E");
                                System.out.println("-------------------\n");
                                System.out.println("1. Deposit.");
                                System.out.println("2. Transfer.");
                                System.out.println("3. Last 5 transactions.");
                                System.out.println("4. User information.");
                                System.out.println("5. Log out.");
                                System.out.print("\nEnter your choice : ");
                                choice = sc.nextInt();
                                sc.nextLine();
                                switch (choice) {
                                    case 1:
                                        System.out.print("Enter amount : ");
                                        while (!sc.hasNextDouble()) {
                                            System.out.println("Invalid amount. Enter again :");
                                            sc.nextLine();
                                        }
                                        amount = sc.nextDouble();
                                        sc.nextLine();
                                        customer.deposit(amount, new Date());
                                        break;

                                    case 2:
                                        System.out.print("Enter beneficiary username : ");
                                        username = sc.next();
                                        sc.nextLine();
                                        System.out.println("Enter amount : ");
                                        while (!sc.hasNextDouble()) {
                                            System.out.println("Invalid amount. Enter again :");
                                            sc.nextLine();
                                        }
                                        amount = sc.nextDouble();
                                        sc.nextLine();
                                        if (amount > 300) {
                                            System.out.println("Transfer limit exceeded. Contact bank manager.");
                                            break;
                                        }
                                        if (bank.customerMap.containsKey(username)) {
                                            Customer payee = bank.customerMap.get(username); //Todo: check
                                            payee.deposit(amount, new Date());
                                            customer.withdraw(amount, new Date());
                                        } else {
                                            System.out.println("Username doesn't exist.");
                                        }
                                        break;

                                    case 3:
                                        for (String transactions : customer.getTransactions()) {
                                            System.out.println(transactions);
                                        }
                                        break;

                                    case 4:
                                        System.out.println("Titularul de cont cu numele: " + customer.getFirstName());
                                        System.out.println("Titularul de cont cu prenumele : " + customer.getLastName());
                                        System.out.println("Titularul de cont cu numele de utilizator : " + customer.getUsername());
                                        System.out.println("Titularul de cont cu addresa : " + customer.getAddress());
                                        System.out.println("Titularul de cont cu numarul de telefon : " + customer.getPhone());
                                        break;
                                    case 5:
                                        continue outer;
                                    default:
                                        System.out.println("Wrong choice !");
                                }
                            }
                        } else {
                            System.out.println("Wrong username/password.");
                        }
                    } else {
                        System.out.println("Wrong username/password.");
                    }
                    break;

                case 3:
                    System.out.println("\nThank you for choosing Bank Of Java.");
                    System.exit(1);
                    break;
                default:
                    System.out.println("Wrong choice !");
            }}}}
Using the java.util library , we call Scanner to read the keyboard. By casting the Customer object through its definition, known as Bank , we create a new object of type Bank() . After some time, we display the start menu. When using nextLine , the number added from the keyboard is read. Below we have a new constructor that saves our map , the client data. Map.put is used to save or update customer data. customer = new Customer(firstName, lastName, address, phone, username, password, new Date());
bank.customerMap.put(username, customer);
If there is a connection, we get a new menu with options. The same approach works by using while and switch to call application functionality. Stage 1: Add money to your current account. Step 2: Display the last 5 transactions. Stage 3: We output the client data from the card to the console. Stage 4: Close the menu. The source code for the program can be found here . I hope this example will help you become more familiar with the use of OOP concepts in Java.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION