Advertisement
Alyks

Untitled

Mar 22nd, 2020
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 18.35 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.io.*;
  4. import java.util.*;
  5.  
  6. class Employee implements Serializable {
  7.     String surname;
  8.     String department;
  9.     double salary;
  10.  
  11.     Employee(String surname, String department, double salary) {
  12.         this.surname = surname;
  13.         this.department = department;
  14.         this.salary = salary;
  15.     }
  16. }
  17.  
  18. class DepartmentData {
  19.     String name;
  20.     double sum = 0;
  21.  
  22.     DepartmentData(String name, double sum) {
  23.         this.name = name;
  24.         this.sum = sum;
  25.     }
  26. }
  27.  
  28. public class Main {
  29.     static void showInfo() {
  30.         System.out.println("Выберите, что вы хотите сделать (введите в консоль значение из квадратных скобок):");
  31.         System.out.println("| Добавить сотрудников [доб] | Изменить данные сотрудников [изм] | Удалить сотрудников [уд] | Вывести информацию о сотрудниках на экран [выв] | Вывести сумму выплат по отделам за месяц [сум] | Завершить работу программы [выход] |");
  32.     }
  33.  
  34.     static String chooseAction(Scanner scan) {
  35.         ArrayList<String> actions = new ArrayList(Arrays.asList("доб", "изм", "уд", "выв", "сум", "выход"));
  36.         String choice = scan.nextLine();
  37.         while (actions.indexOf(choice) == -1) {
  38.             System.out.println("Вы должны выбрать существующее действие.");
  39.             choice = scan.nextLine();
  40.         }
  41.         return choice;
  42.     }
  43.  
  44.     static String makeChoice(ArrayList<String> choices, Scanner scan) {
  45.         String choice = "";
  46.         while (choices.indexOf(choice) == -1) {
  47.             System.out.println("Введите либо [д], либо [н]");
  48.             choice = scan.nextLine();
  49.         }
  50.         return choice;
  51.     }
  52.  
  53.     static int changeEmployeeData(Employee emp, Scanner scan, int changes) {
  54.         String choice = "";
  55.         ArrayList<String> choices = new ArrayList(Arrays.asList("д", "н"));
  56.         boolean notCorrect = true;
  57.         while (notCorrect) {
  58.             System.out.println("Хотите изменить фамилию?");
  59.             choice = makeChoice(choices, scan);
  60.             if (choice.equals("д")) {
  61.                 System.out.println("Введите новую фамилию");
  62.                 String surname = scan.nextLine();
  63.                 if (surname.length() > 0) {
  64.                     emp.surname = surname;
  65.                     System.out.println("Фамилия успешно изменена, хотите продолжить изменение данных?");
  66.                     notCorrect = false;
  67.                     changes++;
  68.                     choice = makeChoice(choices, scan);
  69.                     if (choice.equals("д"))
  70.                         changeEmployeeData(emp, scan, changes);
  71.                 } else
  72.                     System.out.println("Фамилия не может быть пустой, повторите ввод.");
  73.             } else {
  74.                 System.out.println("Хотите изменить наименование отдела?");
  75.                 choice = makeChoice(choices, scan);
  76.                 if (choice.equals("д")) {
  77.                     System.out.println("Введите наименование отдела");
  78.                     String department = scan.nextLine();
  79.                     if (department.length() > 0) {
  80.                         emp.department = department;
  81.                         System.out.println("Наименование отдела успешно изменено, хотите продолжить изменение данных?");
  82.                         notCorrect = false;
  83.                         changes++;
  84.                         choice = makeChoice(choices, scan);
  85.                         if (choice.equals("д"))
  86.                             changeEmployeeData(emp, scan, changes);
  87.                     } else
  88.                         System.out.println("Название отдела не может быть пустым, повторите ввод.");
  89.                 } else {
  90.                     System.out.println("Хотите изменить размер заработной платы?");
  91.                     choice = makeChoice(choices, scan);
  92.                     if (choice.equals("д")) {
  93.                         System.out.println("Введите размер заработной платы");
  94.                         try {
  95.                             double salary = Double.parseDouble(scan.nextLine());
  96.                             if (salary > -1) {
  97.                                 notCorrect = false;
  98.                                 emp.salary = salary;
  99.                                 System.out.println("Заработная плата успешно изменена");
  100.                                 changes++;
  101.                             } else {
  102.                                 notCorrect = true;
  103.                                 System.out.println("Заработная плата не может быть отрицательной, повторите ввод");
  104.                             }
  105.                         } catch (Exception err) {
  106.                             System.out.println("Заработная плата должна быть числом");
  107.                         }
  108.                     }
  109.                 }
  110.             }
  111.         }
  112.         return changes;
  113.     }
  114.  
  115.     static void addData(Scanner scan) {
  116.         ArrayList<Employee> data = new ArrayList<Employee>();
  117.         boolean continueCycle = true;
  118.         boolean notCorrect = true;
  119.         System.out.println("Если хотите прекратить ввод, введите [стоп] вместо фамилии сотрудника");
  120.         while (continueCycle) {
  121.             String surname = "";
  122.             String department = "";
  123.             double salary = 0;
  124.             while (notCorrect) {
  125.                 System.out.println("Введите фамилию сотрудника");
  126.                 surname = scan.nextLine();
  127.                 if(surname.length() > 0) {
  128.                     if (surname.equals("стоп")) {
  129.                         continueCycle = false;
  130.                         notCorrect = false;
  131.                     } else {
  132.                         System.out.println("Введите наименование отдела");
  133.                         department = scan.nextLine();
  134.                         if(department.length() > 0) {
  135.                             System.out.println("Введите заработную плату сотрудника");
  136.                             try {
  137.                                 salary = Double.parseDouble(scan.nextLine());
  138.                                 if (salary > -1)
  139.                                     notCorrect = false;
  140.                                 else {
  141.                                     notCorrect = true;
  142.                                     System.out.println("Заработная плата не может быть отрицательной, повторите ввод");
  143.                                 }
  144.                             } catch (Exception err) {
  145.                                 notCorrect = true;
  146.                                 System.out.println("Возникла ошибка при вводе данных, повторите ввод.");
  147.                             }
  148.                         } else
  149.                             System.out.println("Название отдела не может быть пустым, повторите ввод.");
  150.                     }
  151.                 } else
  152.                     System.out.println("Фамилия не может быть пустой, повторите ввод.");
  153.             }
  154.             if (!surname.equals("стоп")) {
  155.                 notCorrect = true;
  156.                 data.add(new Employee(surname, department, salary));
  157.             }
  158.         }
  159.         saveDataToFile(data, scan, true);
  160.         showInfo();
  161.         executeAction(chooseAction(scan), scan);
  162.     }
  163.  
  164.     static void createNewFile(ArrayList<Employee> data, String filePath) {
  165.         try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))) {
  166.             oos.writeInt(data.size());
  167.             for (Employee emp : data)
  168.                 oos.writeObject(emp);
  169.             System.out.println("Данные успешно сохранены в файл " + filePath);
  170.         } catch (Exception err) {
  171.             System.out.println("Не удалось сохранить данные в файл.");
  172.         }
  173.     }
  174.  
  175.     static void updateFile(ArrayList<Employee> newData, Scanner scan, String filePath) {
  176.         ArrayList<Employee> data = grabData(scan, false, filePath);
  177.         data.addAll(newData);
  178.         try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))) {
  179.             oos.writeInt(data.size());
  180.             for (Employee emp : data)
  181.                 oos.writeObject(emp);
  182.             System.out.println("Данные успешно обновлены в файле " + filePath);
  183.         } catch (Exception err) {
  184.             System.out.println("Не удалось обновить данные в файле.");
  185.         }
  186.     }
  187.  
  188.     static void saveDataToFile(ArrayList<Employee> data, Scanner scan, boolean update) {
  189.         System.out.println("Введите [д], если хотите сохранить данные в файл.");
  190.         String choice = scan.nextLine();
  191.         if (choice.equals("д")) {
  192.             System.out.println("Введите имя файла");
  193.             String filePath = scan.nextLine() + ".dat";
  194.             File file = new File(filePath);
  195.             if (update && file.exists()) {
  196.                 System.out.println("Файл с таким именем уже существует. Хотите его обновить? [д/н] (При выборе [н] создастся новый файл)");
  197.                 choice = scan.nextLine();
  198.                 if (choice.equals("д"))
  199.                     updateFile(data, scan, filePath);
  200.                 else
  201.                     createNewFile(data, filePath);
  202.             } else
  203.                 createNewFile(data, filePath);
  204.         }
  205.     }
  206.  
  207.     static void changeData(Scanner scan) {
  208.         ArrayList<Employee> data = grabData(scan, true, null);
  209.         if (data.size() > 0) {
  210.             boolean continueCycle = true;
  211.             boolean notCorrect = true;
  212.             int changedCount = 0;
  213.             while (continueCycle) {
  214.                 System.out.println("Введите номер сотрудника, данные которого хотите изменить, либо [стоп], чтобы вернуться в меню");
  215.                 while (notCorrect) {
  216.                     String input = scan.nextLine();
  217.                     String choice = "";
  218.                     if (input.equals("стоп")) {
  219.                         notCorrect = false;
  220.                         continueCycle = false;
  221.                     } else {
  222.                         try {
  223.                             int changeNum = Integer.parseInt(input);
  224.                             Employee emp = data.get(changeNum - 1);
  225.                             changedCount = changeEmployeeData(emp, scan, 0);
  226.                             notCorrect = false;
  227.                         } catch (Exception err) {
  228.                             System.out.println("Сотрудник с таким номером не найден, повторите ввод.");
  229.                         }
  230.                     }
  231.                 }
  232.                 notCorrect = true;
  233.             }
  234.             if (changedCount > 0)
  235.                 saveDataToFile(data, scan, false);
  236.         }
  237.         showInfo();
  238.         executeAction(chooseAction(scan), scan);
  239.     }
  240.  
  241.     static void deleteData(Scanner scan) {
  242.         ArrayList<Employee> data = grabData(scan, true, null);
  243.         if (data.size() > 0) {
  244.             boolean continueCycle = true;
  245.             boolean notCorrect = true;
  246.             int deletedCount = 0;
  247.             while (continueCycle) {
  248.                 System.out.println("Введите номер сотрудника, которого хотите удалить, либо [стоп], чтобы вернуться в меню");
  249.                 while (notCorrect) {
  250.                     String input = scan.nextLine();
  251.                     if (input.equals("стоп")) {
  252.                         notCorrect = false;
  253.                         continueCycle = false;
  254.                     } else {
  255.                         try {
  256.                             int deleteNum = Integer.parseInt(input);
  257.                             data.remove(deleteNum - 1);
  258.                             deletedCount++;
  259.                             System.out.println("Сотрудник № " + deleteNum + " успешно удален.");
  260.                             notCorrect = false;
  261.                         } catch (Exception err) {
  262.                             System.out.println("Сотрудник с таким номером не найден, повторите ввод.");
  263.                             notCorrect = true;
  264.                         }
  265.                     }
  266.                 }
  267.                 notCorrect = true;
  268.             }
  269.             if (deletedCount > 0)
  270.                 saveDataToFile(data, scan, false);
  271.         }
  272.         showInfo();
  273.         executeAction(chooseAction(scan), scan);
  274.     }
  275.  
  276.     static void showData(Scanner scan) {
  277.         grabData(scan, true, null);
  278.         showInfo();
  279.         executeAction(chooseAction(scan), scan);
  280.     }
  281.  
  282.     static ArrayList<Employee> grabData(Scanner scan, boolean show, String filePath) {
  283.         if (filePath == null) {
  284.             System.out.println("Введите имя файла");
  285.             filePath = scan.nextLine() + ".dat";
  286.         }
  287.         ArrayList<Employee> data = new ArrayList<Employee>();
  288.         try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath))) {
  289.             int size = ois.readInt();
  290.             for (int i = 0; i < size; i++) {
  291.                 Employee emp = (Employee) ois.readObject();
  292.                 data.add(emp);
  293.             }
  294.             if (show) {
  295.                 if(data.size() > 0) {
  296.                     System.out.println("Данные, записанные в файле:");
  297.                     showArr(data);
  298.                 } else
  299.                     System.out.println("В файле не найдено ни одной записи");
  300.             }
  301.         } catch (Exception err) {
  302.             System.out.println("Произошла ошибка при чтении файла. Убедитесь, что такой файл существует.");
  303.         }
  304.         return data;
  305.     }
  306.  
  307.     static ArrayList<DepartmentData> grabDepartments(ArrayList<Employee> data) {
  308.         ArrayList<DepartmentData> departments = new ArrayList<DepartmentData>();
  309.         for (Employee emp : data) {
  310.             DepartmentData department = grabCurrentDepartment(emp.department, departments);
  311.             if (department == null)
  312.                 departments.add(new DepartmentData(emp.department, emp.salary));
  313.             else
  314.                 department.sum += emp.salary;
  315.         }
  316.         return departments;
  317.     }
  318.  
  319.     static DepartmentData grabCurrentDepartment(String departmentName, ArrayList<DepartmentData> departments) {
  320.         boolean isInArr = false;
  321.         int i = 0;
  322.         DepartmentData department = null;
  323.         while (!isInArr && i < departments.size()) {
  324.             DepartmentData temp = departments.get(i);
  325.             if (temp.name.equals(departmentName)) {
  326.                 isInArr = true;
  327.                 department = temp;
  328.             }
  329.             i++;
  330.         }
  331.         return department;
  332.     }
  333.  
  334.     static void sortDepartments(ArrayList<DepartmentData> departments) {
  335.         for (int i = 0; i < departments.size(); i++) {
  336.             for (int j = 1; j < departments.size() - i; j++) {
  337.                 DepartmentData prev = departments.get(j - 1);
  338.                 DepartmentData curr = departments.get(j);
  339.                 if (curr.name.compareToIgnoreCase(prev.name) < 0) {
  340.                     departments.set(j, prev);
  341.                     departments.set(j - 1, curr);
  342.                 }
  343.             }
  344.         }
  345.     }
  346.  
  347.     static void showDepartmentSum(Scanner scan) {
  348.         ArrayList<Employee> data = grabData(scan, false, null);
  349.         ArrayList<DepartmentData> departments = grabDepartments(data);
  350.         sortDepartments(departments);
  351.         for (DepartmentData department : departments) {
  352.             System.out.println(department.name);
  353.             System.out.println("Общая сумма выплат за месяц по отделу = " + department.sum + "\n");
  354.         }
  355.         showInfo();
  356.         executeAction(chooseAction(scan), scan);
  357.     }
  358.  
  359.     static void showArr(ArrayList<Employee> data) {
  360.         for (int i = 0; i < data.size(); i++) {
  361.             Employee emp = data.get(i);
  362.             System.out.println("Сотрудник №" + (i + 1));
  363.             System.out.println("Фамилия: " + emp.surname);
  364.             System.out.println("Наименование отдела: " + emp.department);
  365.             System.out.println("Заработная плата: " + emp.salary + "\n");
  366.         }
  367.     }
  368.  
  369.     static void executeAction(String action, Scanner scan) {
  370.         if (action.equals("доб"))
  371.             addData(scan);
  372.         else if (action.equals("изм"))
  373.             changeData(scan);
  374.         else if (action.equals("уд"))
  375.             deleteData(scan);
  376.         else if (action.equals("выв"))
  377.             showData(scan);
  378.         else if (action.equals("сум"))
  379.             showDepartmentSum(scan);
  380.         else if (action.equals("выход"))
  381.             System.exit(0);
  382.     }
  383.  
  384.     public static void main(String[] args) {
  385.         System.out.println("Данная программа позволяет работать со сведениями о месячной заработной плате сотрудников отдела.\n");
  386.         Scanner scan = new Scanner(System.in);
  387.         showInfo();
  388.         String action = chooseAction(scan);
  389.         executeAction(action, scan);
  390.     }
  391. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement