Simple bank in java

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Banking Application using Java 8, Sprint Boot, Spring Security and H2 Database

License

sbathina/BankApp

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Banking Application using Java8, Spring Boot, Spring Security and H2 DB

RESTful API to simulate simple banking operations.

  • CRUD operations for customers and accounts.
  • Support deposits and withdrawals on accounts.
  • Internal transfer support (i.e. a customer may transfer funds from one account to another).
git clone https://github.com/sbathina/BankApp 

Refer to the following link for instructions:

https://projectlombok.org/setup/eclipse 
- Import existing maven project - Run mvn clean install - If using STS, Run As Spring Boot App 
spring-boot-starter-actuator spring-boot-starter-data-jpa spring-boot-starter-security spring-boot-starter-web spring-boot-devtools h2 - Inmemory database lombok - to reduce boilerplate code springfox-swagger2 springfox-swagger-ui spring-boot-starter-test spring-security-test 

Please find the Rest API documentation in the below url

http://localhost:8989/bank-api/swagger-ui.html 

Make sure to use jdbc:h2:mem:testdb as your jdbc url. If you intend to you use custom database name, please define datasource properties in application.yml

http://localhost:8989/bank-api/h2-console/ 

Testing the Bank APP Rest Api

  1. Please use the Swagger url to perform CRUD operations.
  2. Browse to /src/test/resources to find sample requests to add customer and accounts.

About

Banking Application using Java 8, Sprint Boot, Spring Security and H2 Database

Читайте также:  Python log in unittest

Источник

Кофе-брейк #201. Как создать консольное банковское приложение на Java

Java-университет

Кофе-брейк #201. Как создать консольное банковское приложение на Java - 1

Источник: MediumСегодня мы разработаем простое Java-приложение для банковской системы. Оно поможет нам лучше понять, как концепции ООП используются в программах на языке Java.Для начала нам понадобится среда Java, установленная на компьютере, желательно Java 11. Далее мы начнем с подробного описания функций консольного приложения. Функционал:

  1. Создание аккаунта;
  2. Вход, выход;
  3. Отображение последних 5 транзакций;
  4. Депозит денежных средств;
  5. Отображение текущей информации о пользователе.

Используемые концепции объектно-ориентированного программирования:

  1. Наследование;
  2. Полиморфизм;
  3. Инкапсуляция.

Разработка приложения

Создадим новый Java-проект в Eclipse или IntelliJ IDEA. Определим новый интерфейс с именем SavingsAccount .

 public interface SavingsAccount

Я реализовал интерфейс, в котором размещен метод deposit . Я вызываю этот метод каждый раз, когда добавляю деньги на текущий счет. Используемая здесь концепция ООП — полиморфизм (методы в интерфейсе не имеют тела). Реализацию этого метода можно найти в классе Customer , переопределив метод с тем же именем и параметрами. Так вы переопределяете метод из родительского интерфейса в дочернем классе. Затем нам понадобится клиент (customer), чтобы добавить деньги на текущий счет. Но сначала давайте определим наш класс Customer .

 public class Customer extends Person implements SavingsAccount < private String username; private String password; private double balance; private ArrayListtransactions = new ArrayList<>(5); public Customer(String firstName, String lastName, String address, String phone, String username, String password, double balance, ArrayList 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 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наследование, поскольку класс Customer получает свойства от класса Person. То есть, практически все атрибуты класса Person наследуются и видны отношения по родительско-дочернему принципу от Person к Customer. Сейчас нам нужен конструктор со всеми атрибутами двух классов и добавление ключевого слова суперконструктора для указания унаследованных атрибутов. Реализуя интерфейс SavingsAccount, мы должны переопределить метод deposit в классе Customer. Для этого мы напишем реализацию метода в этом классе. Кроме того, список транзакций инициализируется для отображения последних пяти транзакций. В конструкторе вызывается метод addTransaction, в котором отображается дата изменений и совершенных транзакций. 
 private void addTransaction(String message) < transactions.add(0, message); if (transactions.size() >5) < transactions.remove(5); transactions.trimToSize(); >> 
 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'; > @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()

В классе Person мы использовали концепцию инкапсуляции , применяя модификатор доступа private для каждого атрибута. Инкапсуляция в Java может быть определена как механизм, с помощью которого методы, работающие с этими данными, объединяются в единое целое. По сути, данные из класса Person доступны только в этом классе, но никак не в других классах или пакетах. И наконец, наш основной класс, названный Bank . Это основной класс, откуда мы запускаем приложение и взаимодействуем с функциональностью всех классов.

 public class Bank < private static double amount = 0; MapcustomerMap; Bank() < customerMap = new HashMap(); > 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 !"); >>>> 

Используя библиотеку java.util , мы вызываем Scanner для чтения данных с клавиатуры. Приводя объект Customer через его определение, известное как Bank , мы создаем новый объект типа Bank() . Через некоторое время выводим стартовое меню. При использовании nextLine считывается число, добавленное с клавиатуры. Ниже у нас есть новый конструктор, который сохраняет нашу map , данные клиента. Map.put используется для сохранения или обновления данных клиентов. customer = new Customer(firstName, lastName, address, phone, username, password, new Date());

 bank.customerMap.put(username, customer); 

При наличии соединения мы получаем новое меню с опциями. Тот же подход работает с использованием while и switch для вызова функционала приложения. Этап 1: Добавляем деньги на текущий счет. Этап 2: Отображаем последние 5 транзакций. Этап 3: Выводим данные клиента с карты в консоль. Этап 4: Закрываем меню. Исходный код программы можно найти здесь. Надеюсь, что этот пример поможет вам лучше познакомиться с использованием концепций ООП в Java.

Источник

Simple bank in java

Simple Banking Application Using Java​

Abstract:

In this modernized world, where time is money, everyone has got the habit of doing their tasks online. Within a click, a task is done. You get this application to make transactions just by sitting in your comfort zone. Every operation like money transfer and balance inquiry can be done in seconds.

Introduction:

Simple Banking Application is a simple Java project for beginners to start their career in coding. You’ll learn about Scanner class to take inputs, and the basics of strings, loops, methods, and conditional statements. Here, simple banking operations like deposit, withdrawal, checking balance, exit, etc.

Explanation:

The first step in building our application is to create a new Java project. We will use the command-line interface to create a new project and set up the project structure. Once the project is set up, we can start writing the code for our application.

The main class of our application will be called “Bank”. In this class, we will define the main method and the basic functionality of our application. The main method will be responsible for displaying the menu to the user and handling the user’s input.

The menu will consist of four options:

The user will be prompted to select an option by entering a number between 1 and 4. If the user enters an invalid option, the application will display an error message and prompt the user to enter a valid option.

Источник

Оцените статью