Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.Scanner;
- record Workers (String name, String otdel, int a,int b,int c) {
- @Override
- public String toString() {
- return String.format("| %-20s | %-20s | %-5d | %-5d | %-5d |",
- this.name, this.otdel, this.a, this.b, this.c);
- }
- }
- record Department (String otdel, int zp, int sum, int count) {
- public Department withCount(int i) {
- return new Department(this.otdel(), this.zp(), this.sum() , i);
- }
- public Department withSum(int i) {
- return new Department(this.otdel(), this.zp(), i, this.count());
- }
- public Department withZp(int i) {
- return new Department(this.otdel, i, this.sum, this.count);
- }
- }
- public class Main {
- enum ErrCode {
- SUCCESS,
- INCORRECT_DATA,
- INCORRECT_NAME,
- EMPTY_LINE,
- NO_SUCH_REC,
- IO_EXCEPTION,
- TO_MUCH_RECORDS,
- }
- enum Choice {
- addRec("Добавить"),
- deleteRec("Удалить"),
- changeRec("Изменить"),
- save("Сохранить изменения"),
- findByName("Найти по фамилии"),
- findByOtdel("Найти по цеху"),
- middRec("Получить сводку"),
- close("Закрыть");
- private final String inf;
- Choice (String infLine) {
- this.inf = infLine;
- }
- private String getInf(){return this.ordinal() + ") " + this.inf;}
- }
- static final int MIN_COUNT = 0,
- MAX_COUNT = 2000000000,
- MIN_KOL = 0,
- MAX_KOL = 200000,
- MAX_REC_COUNT = 999;
- static final String[] ERRORS = {"Удача",
- "Некорректные данные(введите число от %d до %d)\n",
- "Имя должно быть максимум 20 символов в длину",
- "Строка пустая, будьте внимательны",
- "Записи с таким номером нет в списке!",
- "Ошибка чтения/записи файла",
- "Записей не может быть больше, чем %d\n"};
- static final String STORAGE_FILE_PATH = "StorageFile.txt",
- BUFFER_FILE_PATH = "BufferFile.txt",
- CORRECTION_FILE_PATH = "CorrectionFile.txt",
- INFORMATION_TEXT = """
- Завод.
- Инструкция:
- 1) Фамилия и цех ограничены 20 символами
- 2) Количество изделий может принимать значения от 0 до 200000
- 3) Чтобы внесенные изменения остались, требуется сохраниться
- или выйти через кнопку
- 4) Стоимость единицы товара: A-50, B-100, C-150
- """,
- START_GRID_LINE = """
- ----------------------------------------------------------------------------
- | № | Фамилия | Цех | A | B | C |
- ----------------------------------------------------------------------------
- """;
- static void printInf(Scanner input) {
- System.out.println(INFORMATION_TEXT);
- System.out.println("Нажмите enter чтобы продолжить");
- input.nextLine();
- }
- static DataOutputStream openFileToWrite(String fileName) throws IOException{
- File file = new File(fileName);
- if (!file.exists())
- file.createNewFile();
- return new DataOutputStream(new FileOutputStream(fileName));
- }
- static DataInputStream openFileToRead(String fileName) throws IOException{
- File file = new File(fileName);
- if (!file.exists()) {
- file.createNewFile();
- }
- return new DataInputStream(new FileInputStream(fileName));
- }
- static Workers readRec(DataInputStream file) throws IOException{
- String name,otdel;
- int a,b,c;
- name = file.readUTF();
- otdel = file.readUTF();
- a = file.readInt();
- b = file.readInt();
- c = file.readInt();
- return new Workers(name, otdel, a, b, c);
- }
- static void writeRec(DataOutputStream file, Workers workers) throws IOException{
- file.writeUTF(workers.name());
- file.writeUTF(workers.otdel());
- file.writeInt(workers.a());
- file.writeInt(workers.b());
- file.writeInt(workers.c());
- }
- static void renameFileTo(String oldName, String newName) {
- File oldFile = new File(newName);
- oldFile.delete();
- File newFile = new File(oldName);
- newFile.renameTo(oldFile);
- }
- static void copyFile(String destFilePath, String soursFilePath) {
- try(DataInputStream inputFile = openFileToRead(soursFilePath);
- DataOutputStream outputFile = openFileToWrite(destFilePath)) {
- while (inputFile.available() > 0)
- writeRec(outputFile, readRec(inputFile));
- } catch (IOException e) {
- System.err.println(ERRORS[ErrCode.IO_EXCEPTION.ordinal()]);
- }
- }
- static void addRecToFile(String fileName, Workers workers) {
- int countRec = 0;
- try(DataOutputStream outputFile = openFileToWrite(BUFFER_FILE_PATH);
- DataInputStream inputFile = openFileToRead(fileName)) {
- while (inputFile.available() > 0) {
- writeRec(outputFile, readRec(inputFile));
- countRec++;
- }
- if (countRec < MAX_REC_COUNT)
- writeRec(outputFile, workers);
- else
- System.err.printf(ERRORS[ErrCode.TO_MUCH_RECORDS.ordinal()], MAX_REC_COUNT);
- } catch (IOException e) {
- System.err.println(ERRORS[ErrCode.IO_EXCEPTION.ordinal()]);
- }
- renameFileTo(BUFFER_FILE_PATH, fileName);
- }
- static void printFile(String fileName) {
- Workers workers;
- String line;
- int count = 0;
- try(DataInputStream file = openFileToRead(fileName)) {
- System.out.printf(START_GRID_LINE);
- while (file.available() > 0) {
- count++;
- workers = readRec(file);
- line = String.format("| %-3d " + workers, count);
- System.out.printf(line + "\n");
- System.out.println("-".repeat(line.length()));
- }
- } catch (IOException e) {
- System.err.println(ERRORS[ErrCode.IO_EXCEPTION.ordinal()]);
- }
- }
- static ErrCode deleteRec(int index) {
- ErrCode err = ErrCode.NO_SUCH_REC;
- try (DataInputStream inputFile = openFileToRead(CORRECTION_FILE_PATH);
- DataOutputStream outputFile = openFileToWrite(BUFFER_FILE_PATH)) {
- for (int i = 1; inputFile.available() > 0; i++)
- if (i != index)
- writeRec(outputFile, readRec(inputFile));
- else {
- err = ErrCode.SUCCESS;
- readRec(inputFile);
- }
- } catch (IOException e) {
- err = ErrCode.IO_EXCEPTION;
- }
- renameFileTo(BUFFER_FILE_PATH, CORRECTION_FILE_PATH);
- return err;
- }
- static ErrCode enterOneNum(int[] numberArr, Scanner input, final int MIN, final int MAX) {
- int number = 0;
- ErrCode err = ErrCode.SUCCESS;
- try {
- number = Integer.parseInt(input.nextLine());
- } catch (NumberFormatException e) {
- err = ErrCode.INCORRECT_DATA;
- }
- if ((err == ErrCode.SUCCESS) && (number < MIN || number > MAX))
- err = ErrCode.INCORRECT_DATA;
- numberArr[0] = err == ErrCode.SUCCESS ? number : 0;
- return err;
- }
- static ErrCode enterNameConsole(String[] nameArr, Scanner input) {
- ErrCode err = ErrCode.SUCCESS;
- nameArr[0] = input.nextLine();
- if (nameArr[0].length() > 20)
- err = ErrCode.INCORRECT_NAME;
- if (nameArr[0].isEmpty())
- err = ErrCode.EMPTY_LINE;
- return err;
- }
- static String getName(Scanner input) {
- String[] nameArr = {""};
- ErrCode err;
- do {
- err = enterNameConsole(nameArr, input);
- if (err != ErrCode.SUCCESS) {
- System.err.println(ERRORS[err.ordinal()]);
- System.err.println("Повторите ввод");
- }
- } while (err != ErrCode.SUCCESS);
- return nameArr[0];
- }
- static int getNumConsole(Scanner input, final int MIN, final int MAX) {
- ErrCode err;
- int[] numberArr = {0};
- do {
- err = enterOneNum(numberArr, input, MIN, MAX);
- if (err != ErrCode.SUCCESS) {
- System.err.printf(ERRORS[err.ordinal()], MIN, MAX);
- System.err.println("Повторите ввод");
- }
- } while (err != ErrCode.SUCCESS);
- return numberArr[0];
- }
- static Workers enterNewWorkersFromConsole(Scanner input) {
- String name;
- String otdel;
- int a, b, c;
- System.out.println("Введите фамилию:");
- name = getName(input);
- System.out.println("Введите цех:");
- otdel = getName(input);
- System.out.println("Введите кол-во изделий категории A:");
- a = getNumConsole(input, MIN_KOL, MAX_KOL);
- System.out.println("Введите кол-во изделий категории B:");
- b = getNumConsole(input, MIN_KOL, MAX_KOL);
- System.out.println("Введите кол-во изделий категории C:");
- c = getNumConsole(input, MIN_KOL, MAX_KOL);
- return new Workers(name, otdel, a, b ,c);
- }
- static ErrCode changeRec(int index, Scanner input) {
- ErrCode err = ErrCode.NO_SUCH_REC;
- try (DataInputStream inputFile = openFileToRead(CORRECTION_FILE_PATH);
- DataOutputStream outputFile = openFileToWrite(BUFFER_FILE_PATH)) {
- for (int i = 1; inputFile.available() > 0; i++)
- if (i != index)
- writeRec(outputFile, readRec(inputFile));
- else {
- err = ErrCode.SUCCESS;
- readRec(inputFile);
- writeRec(outputFile, enterNewWorkersFromConsole(input));
- }
- } catch (IOException e) {
- err = ErrCode.IO_EXCEPTION;
- }
- renameFileTo(BUFFER_FILE_PATH, CORRECTION_FILE_PATH);
- return err;
- }
- static void printMenu() {
- Choice[] choices = Choice.values();
- for (Choice choice : choices) {
- System.out.println(choice.getInf());
- }
- }
- static Choice getChoice(Scanner input) {
- int choice;
- int maxChoice = Choice.values().length - 1;
- choice = getNumConsole(input, 0, maxChoice);
- return Choice.values()[choice];
- }
- static void findRec(Choice choice, String criteria) {
- Workers workers;
- try (DataInputStream inputFile = openFileToRead(CORRECTION_FILE_PATH);
- DataOutputStream outputFile = openFileToWrite(BUFFER_FILE_PATH)) {
- while (inputFile.available() > 0) {
- workers = readRec(inputFile);
- boolean isValid = false;
- if (choice.equals(Choice.findByName)) {
- if (workers.toString().contains(criteria)) {
- isValid = true;
- }
- } else {
- if (workers.toString().contains(criteria)) {
- isValid = true;
- }
- }
- if (isValid) {
- writeRec(outputFile, workers);
- }
- }
- } catch (IOException e) {
- System.err.println(ERRORS[ErrCode.IO_EXCEPTION.ordinal()]);
- }
- printFile(BUFFER_FILE_PATH);
- new File(BUFFER_FILE_PATH).delete();
- }
- public static void middRec() {
- Workers [] workers;
- int sA = 50;
- int sB = 100;
- int sC = 150;
- try {
- DataInputStream inputFile = openFileToRead(CORRECTION_FILE_PATH);
- workers = readAllRec(inputFile);
- inputFile.close();
- int departmentCount = 0;
- Department[] departments = new Department[0];
- for (int i = 0; i < workers.length; i++) {
- Workers currentWorker = workers[i];
- boolean found = false;
- for (int j = 0; j < departmentCount; j++) {
- if (currentWorker.otdel().equals(departments[j].otdel())) {
- departments[j] = departments[j].withSum(departments[j].sum() + currentWorker.a() + currentWorker.b() + currentWorker.c());
- departments[j] = departments[j].withZp(departments[j].zp() + (currentWorker.a() * sA) + (currentWorker.b() * sB) + (currentWorker.c() * sC));
- departments[j] = departments[j].withCount(departments[j].count() + 1);
- found = true;
- }
- }
- if (!found) {
- Department[] newDepartments = new Department[departmentCount + 1];
- System.arraycopy(departments, 0, newDepartments, 0, departmentCount);
- departments = newDepartments;
- departments[departmentCount] = new Department(currentWorker.otdel(), (currentWorker.a() * sA) + (currentWorker.b() * sB) + (currentWorker.c() * sC), currentWorker.a() + currentWorker.b() + currentWorker.c(), 1);
- departmentCount++;
- }
- }
- System.out.println("Сводка:");
- for (int i = 0; i < departmentCount; i++) {
- System.out.println("Цех: " + departments[i].otdel());
- System.out.println("Кол-во изделий: " + departments[i].sum());
- System.out.println("Зп: " + departments[i].zp());
- double averageSalary;
- if (departments[i].count() > 0) {
- averageSalary = (double) departments[i].zp() / departments[i].count();
- } else {
- averageSalary = 0;
- }
- System.out.println("Средняя зп: " + averageSalary);
- System.out.println();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- private static Workers[] readAllRec(DataInputStream inputFile) throws IOException {
- int initialCapacity = 10;
- Workers[] workersArray = new Workers[initialCapacity];
- int size = 0;
- try {
- while (true) {
- String name, otdel;
- int a, b, c;
- name = inputFile.readUTF();
- otdel = inputFile.readUTF();
- a = inputFile.readInt();
- b = inputFile.readInt();
- c = inputFile.readInt();
- Workers worker = new Workers(name, otdel, a, b, c);
- if (size == workersArray.length) {
- int newCapacity = size * 2;
- Workers[] newArray = new Workers[newCapacity];
- System.arraycopy(workersArray, 0, newArray, 0, size);
- workersArray = newArray;
- }
- workersArray[size] = worker;
- size++;
- }
- } catch (EOFException e) {
- }
- Workers[] finalArray = new Workers[size];
- System.arraycopy(workersArray, 0, finalArray, 0, size);
- return finalArray;
- }
- static boolean doFunction(Scanner input) {
- Choice choice = getChoice(input);
- ErrCode err;
- boolean isClose = false;
- switch (choice) {
- case addRec -> {
- Workers workers = enterNewWorkersFromConsole(input);
- addRecToFile(CORRECTION_FILE_PATH, workers);
- }
- case deleteRec -> {
- System.out.print("Введите номер записи, которую хотите удалить: ");
- int index = getNumConsole(input, 0, MAX_COUNT);
- err = deleteRec(index);
- if (err != ErrCode.SUCCESS) {
- System.err.println(ERRORS[err.ordinal()]);
- }
- }
- case changeRec -> {
- System.out.print("Введите номер записи, которую хотите изменить: ");
- int index = getNumConsole(input, 0, MAX_COUNT);
- err = changeRec(index, input);
- if (err != ErrCode.SUCCESS) {
- System.err.println(ERRORS[err.ordinal()]);
- }
- }
- case save -> {
- copyFile(STORAGE_FILE_PATH, CORRECTION_FILE_PATH);
- }
- case findByName -> {
- System.out.print("Введите фамилию , по которой хотите найти : ");
- String name = getName(input);
- findRec(choice, name);
- System.out.println("Нажмите enter чтобы продолжить");
- input.nextLine();
- }
- case findByOtdel -> {
- System.out.print("Введите цех , по которому хотите найти: ");
- String otdel = getName(input);
- findRec(choice, otdel);
- System.out.println("Нажмите enter чтобы продолжить");
- input.nextLine();
- }
- case middRec -> {
- middRec();
- System.out.println("Нажмите enter чтобы продолжить");
- input.nextLine();
- }
- case close -> {
- renameFileTo(CORRECTION_FILE_PATH, STORAGE_FILE_PATH);
- isClose = true;
- }
- }
- return isClose;
- }
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- printInf(input);
- copyFile(CORRECTION_FILE_PATH, STORAGE_FILE_PATH);
- boolean isClose;
- do {
- printFile(CORRECTION_FILE_PATH);
- printMenu();
- isClose = doFunction(input);
- } while (!isClose);
- input.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement