123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343 |
- package com.company;
- import java.io.*;
- import java.util.ArrayList;
- /**
- * Класс реализующий "банк"
- */
- public class Bank {
- /**
- * Список клиентов банка
- */
- private static ArrayList<User> users = new ArrayList<>();
- /**
- * Голова списка счетов банка
- */
- private static Bill head;
- /**
- * Счётчик клиентов банка. Обновлятся при добавлении нового клиента или удалении старого счёта.
- */
- private static int count;
- /**
- * Наименование банка
- */
- private static String name;
- /**
- * Сохранить в файл список всех зарегистрированных клиентов
- */
- public static void saveClients() {
- try {
- FileOutputStream fos = new FileOutputStream("clients.bin");
- ObjectOutputStream objectOutputStream = new ObjectOutputStream(fos);
- objectOutputStream.writeObject(users);
- objectOutputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * Загрузить из файла список всех зарегистрированных клиентов
- */
- public static void loadClients() {
- try {
- FileInputStream fos = new FileInputStream("clients.bin");
- ObjectInputStream objectOutputStream = new ObjectInputStream(fos);
- Object o = objectOutputStream.readObject();
- ArrayList<?> array;
- if (o instanceof ArrayList<?>) {
- array = (ArrayList<?>) o;
- for (Object object : array) {
- if (object instanceof User) {
- User user = (User) object;
- users.add(user);
- }
- }
- }
- for (User u : users) {
- System.out.println(u.getUuid());
- }
- objectOutputStream.close();
- } catch (IOException | ClassNotFoundException e) {
- e.printStackTrace();
- }
- }
- /**
- * Сохранить список всех счетов в файл
- */
- public static void saveBills() {
- // Пересчитать количество счетов
- count = 0;
- Bill current = head;
- while (current != null) {
- count++;
- current = current.next;
- }
- current = head;
- Bill[] bills = new Bill[count];
- count = 0;
- while (current != null) {
- bills[count++] = current;
- current = current.next;
- }
- try {
- FileOutputStream fos = new FileOutputStream("bills.bin");
- ObjectOutputStream objectOutputStream = new ObjectOutputStream(fos);
- objectOutputStream.writeObject(bills);
- objectOutputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * Загрузить из файла список всех счетов
- */
- public static void loadBills() {
- try {
- FileInputStream fos = new FileInputStream("bills.bin");
- ObjectInputStream objectInputStream = new ObjectInputStream(fos);
- Object o = objectInputStream.readObject();
- if (o instanceof Bill[]) {
- Bill[] bills = (Bill[]) o;
- Bill current = head;
- count = 0;
- for (Object object : bills) {
- if (object instanceof Bill) {
- Bill bill = (Bill) object;
- if (count == 0) {
- head = bill;
- current = head;
- count++;
- } else {
- current.next = bill;
- current = current.next;
- }
- }
- }
- }
- objectInputStream.close();
- } catch (IOException | ClassNotFoundException e) {
- e.printStackTrace();
- }
- }
- /**
- * Возвращает количество клиентов
- *
- * @return размер списка
- */
- public static int getClientCount() {
- return count;
- }
- public static void registerUser(User user) {
- users.add(user);
- }
- public static boolean authorizedUser(String login, String password) {
- for (User u : users) {
- if (u.check(login, password)) {
- return true;
- }
- }
- return false;
- }
- /**
- * Возвращает наименование банка
- *
- * @return название
- */
- public static String getName() {
- return name;
- }
- /**
- * Задать наименование банка
- *
- * @param name имя банка
- */
- public static void setName(String name) {
- Bank.name = name;
- }
- /**
- * Авторизация клиента в системе
- *
- * @param bill номер счёта
- * @param pin пин-код
- * @return true, если данные верны
- */
- public static boolean authorization(String bill, String pin) {
- Bill pointer = head;
- while (pointer != null) {
- if (pointer.getNumber().equals(bill)) {
- if (pointer.checkPincode(pin)) {
- return true;
- }
- }
- pointer = pointer.next;
- }
- return false;
- }
- /**
- * Вставить новый элемент в конец списока (открытие нового счёта)
- *
- * @param user пользователь, открывающий счёт
- * @param balance начальный баланс
- * @return регистрационные данные
- */
- public static SecretData insert(User user, double balance) {
- Bill newBill = new Bill(user.getUuid(), balance, count);
- if (head == null) {
- head = newBill;
- } else {
- Bill last = head;
- while (last.next != null) {
- last = last.next;
- }
- last.next = newBill;
- }
- count++;
- return newBill.getSecretData();
- }
- /**
- * Вставить новый элемент после указанного indexAfter (открытие ранее удалённого счёта)
- *
- * @param user пользователь, открывающий счёт
- * @param indexAfter индекс элемента, после которого будет вставлен новыйа
- * @param balance начальный баланс
- */
- public static void insertAt(User user, int indexAfter, double balance) {
- Bill newBill = new Bill(user.getUuid(), balance, count);
- Bill current = head;
- if (indexAfter > count) {
- while (current.next != null) {
- current = current.next;
- }
- } else {
- int index = 1;
- while (index < indexAfter) {
- current = current.next;
- index++;
- }
- newBill.next = current.next;
- }
- current.next = newBill;
- }
- /**
- * Вывод информации о всех клиентах в консоль
- */
- public static void showClientsInfo() {
- Bill current = head;
- System.out.println("\nStart client list info:");
- while (current != null) {
- System.out.printf("Bill number: %s; Balance: %.2f;\n", current.getNumber(), current.getBalance());
- current = current.next;
- }
- System.out.println("End client list info.\n");
- }
- /**
- * Пополнить баланс (только свой счёт)
- *
- * @param value пополняемое значение
- * @param bill пополняемый номер счёта
- */
- public static void deposit(double value, String bill) {
- Bill current = head;
- while (current != null) {
- if (bill.equals(current.getNumber())) {
- current.deposit(value);
- break;
- }
- current = current.next;
- }
- }
- /**
- * Списать баланс
- *
- * @param value списываемое значение
- * @param bill номер счёта для списания
- */
- public static void withdraw(double value, String bill) {
- Bill current = head;
- while (current != null) {
- if (bill.equals(current.getNumber())) {
- current.withdraw(value);
- break;
- }
- current = current.next;
- }
- }
- /**
- * Разорвать договор с банком (удалить счёт)
- *
- * @param bill номер удаляемого счёта
- */
- public static void delete(String bill) {
- Bill current = head;
- Bill last = head;
- while (current != null) {
- if (bill.equals(current.getNumber())) {
- last.next = current.next;
- break;
- }
- last = current;
- current = current.next;
- }
- }
- }
|