Advertisement
Alyks

Untitled

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