redmanexe

Lab3Challenge2Java

Nov 2nd, 2024 (edited)
17
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.98 KB | None | 0 0
  1. package dev.rexe;
  2.  
  3. import java.io.*;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Scanner;
  7.  
  8. public class Main {
  9.     public final static String DEFAULT_INPUT_FILE = "input.txt";
  10.     public final static String DEFAULT_OUTPUT_FILE = "output.txt";
  11.  
  12.     public final static int PRINT_TYPE_MIN = 0;
  13.     public final static int PRINT_TYPE_MAX = 2;
  14.  
  15.     public final static int SCAN_TYPE_MIN = 0;
  16.     public final static int SCAN_TYPE_MAX = 1;
  17.  
  18.     public static void main(String[] args) {
  19.         Scanner scanner = new Scanner(System.in);
  20.  
  21.         String value, res;
  22.         System.out.println("2. Дана непустая последовательность символов, требуется построить и напечатать множество, элементами которого являются встречающиеся в последовательности знаки арифметических операций и чётные цифры.");
  23.         value = Main.readString(scanner);
  24.         System.out.println(value);
  25.         res = Main.calculate(value);
  26.         Main.printResult(scanner, res);
  27.  
  28.         scanner.close();
  29.     }
  30.  
  31.     public static String calculate(String input) {
  32.         HashSet<Character> set = new HashSet<>(List.of('+', '-', '*', '/', '.', ',', '=', '^', '%', '0', '2', '4', '6', '8'));
  33.         StringBuilder calculated = new StringBuilder();
  34.         for (char c : input.toCharArray()) {
  35.             if (set.contains(c))
  36.                 calculated.append(c);
  37.         }
  38.  
  39.         return calculated.toString();
  40.     }
  41.  
  42.     public static boolean checkFileAvailability(String filePath, boolean read) {
  43.         boolean fl;
  44.         fl = true;
  45.         try {
  46.             File file = new File(filePath);
  47.             if (!read) {
  48.                 BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file));
  49.                 fileWriter.close();
  50.             } else {
  51.                 BufferedReader fileReader = new BufferedReader(new FileReader(file));
  52.                 fileReader.close();
  53.             }
  54.         } catch (Exception e) {
  55.             fl = false;
  56.         }
  57.         if (!isTextFile(filePath)) {
  58.             fl = false;
  59.         }
  60.         return fl;
  61.     }
  62.     public static boolean isTextFile(String filePath) {
  63.         boolean isTxt;
  64.         isTxt = (filePath.length() > 4 &&
  65.                 filePath.charAt(filePath.length() - 4) == '.' &&
  66.                 filePath.charAt(filePath.length() - 3) == 't' &&
  67.                 filePath.charAt(filePath.length() - 2) == 'x' &&
  68.                 filePath.charAt(filePath.length() - 1) == 't');
  69.  
  70.         return isTxt;
  71.     }
  72.     public static String readString(Scanner scanner) {
  73.         String value;
  74.         int type;
  75.         System.out.println("\nКак считать значения для поиска решения?");
  76.         System.out.println("0 - Из ввода с клавиатуры (консоль)");
  77.         System.out.println("1 - Из файла");
  78.         type = takeIntValueInRangeFromConsole(scanner, "Выбранный вариант ввода: ", SCAN_TYPE_MIN, SCAN_TYPE_MAX);
  79.         if (type == 1) {
  80.             value = readStringFromFile(scanner);
  81.         } else {
  82.             value = readStringFromConsole(scanner);
  83.         }
  84.  
  85.         return value;
  86.     }
  87.     public static String takeValueFromFile(BufferedReader reader) {
  88.         boolean isValue;
  89.         StringBuilder value = new StringBuilder();
  90.         isValue = true;
  91.         try {
  92.             while (isValue) {
  93.                 int c = reader.read();
  94.                 if (c != -1 && c != '\n' && c != ' ') {
  95.                     value.append((char) c);
  96.                 } else
  97.                     isValue = false;
  98.             }
  99.         } catch (IOException e) {}
  100.  
  101.         return value.toString();
  102.     }
  103.     public static String readStringFromFile(Scanner scanner) {
  104.         String value = "";
  105.         boolean isInCorrect = true;
  106.         while (isInCorrect) {
  107.             File file = takeCorrectFile(scanner, true);
  108.             isInCorrect = false;
  109.             try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
  110.                 value = takeValueFromFile(reader);
  111.             } catch (IOException e) {
  112.                 isInCorrect = true;
  113.                 System.out.println("Этот файл не существует! Введите путь до существующего файла!");
  114.             }
  115.         }
  116.  
  117.         return value;
  118.     }
  119.     public static String readStringFromConsole(Scanner scanner) {
  120.         String value;
  121.         System.out.print("Строка для решения: ");
  122.         value = scanner.nextLine();
  123.  
  124.         return value;
  125.     }
  126.     public static int takeIntValueFromConsole(Scanner scanner, String text) {
  127.         boolean isInCorrect;
  128.         int value;
  129.         isInCorrect = true;
  130.         value = 0;
  131.         while (isInCorrect) {
  132.             System.out.print(text);
  133.             try {
  134.                 value = Integer.parseInt(scanner.nextLine());
  135.                 isInCorrect = false;
  136.             } catch (NumberFormatException e) {
  137.                 System.out.println("Введите число, а не строку или что-то иное!");
  138.             }
  139.         }
  140.  
  141.         return value;
  142.     }
  143.     public static int takeIntValueInRangeFromConsole(Scanner scanner, String text, int min, int max) {
  144.         boolean isInCorrect;
  145.         int value;
  146.         isInCorrect = true;
  147.         value = 0;
  148.         while (isInCorrect) {
  149.             value = takeIntValueFromConsole(scanner, text);
  150.             isInCorrect = false;
  151.             if ((value < min || value > max)) {
  152.                 isInCorrect = true;
  153.                 System.out.println("Значение должно находится в границах от " + min + " до " + max + "!");
  154.             }
  155.         }
  156.  
  157.         return value;
  158.     }
  159.     public static void printResult(Scanner scanner, String value) {
  160.         boolean saved;
  161.         int type;
  162.         System.out.println("\nКуда вывести результат решения?");
  163.         System.out.println("0 - Только консоль");
  164.         System.out.println("1 - Только в файл");
  165.         System.out.println("2 - И в файл, и в консоль");
  166.         type = takeIntValueInRangeFromConsole(scanner, "Выбранный вариант вывода: ", PRINT_TYPE_MIN, PRINT_TYPE_MAX);
  167.         saved = false;
  168.  
  169.         switch (type) {
  170.             case 0 -> {
  171.                 System.out.println("\nМножество арифметических знаков и чётных чисел: " + value);
  172.             }
  173.             case 1 -> {
  174.                 File output = takeCorrectFile(scanner, false);
  175.                 saved = saveResultIntoFile(output, value);
  176.             }
  177.             case 2 -> {
  178.                 File output = takeCorrectFile(scanner, false);
  179.                 saved = saveResultIntoFile(output, value);
  180.                 System.out.println("\nМножество арифметических знаков и чётных чисел: " + value);
  181.             }
  182.         }
  183.  
  184.         if (saved)
  185.             System.out.println("Результат записан в выходной файл!");
  186.     }
  187.     public static File takeCorrectFile(Scanner scanner, boolean input) {
  188.         boolean isInCorrect;
  189.         String value = "";
  190.         isInCorrect = true;
  191.         while(isInCorrect) {
  192.             if (input)
  193.                 System.out.print("Введите путь до входного файла (пустая строка – " + DEFAULT_INPUT_FILE + "): ");
  194.             else
  195.                 System.out.print("Введите путь до выходного файла (пустая строка – " + DEFAULT_OUTPUT_FILE + "): ");
  196.             value = scanner.nextLine();
  197.             isInCorrect = false;
  198.             if (value.isEmpty()) {
  199.                 if (input)
  200.                     value = DEFAULT_INPUT_FILE;
  201.                 else
  202.                     value = DEFAULT_OUTPUT_FILE;
  203.             }
  204.             if (!checkFileAvailability(value, input)) {
  205.                 isInCorrect = true;
  206.                 System.out.println("Путь ведёт до файла, который недоступен или который не является текстовым файлом!");
  207.             }
  208.         }
  209.         File result = new File(value);
  210.         return result;
  211.     }
  212.     public static boolean saveResultIntoFile(File output, String value) {
  213.         boolean saved;
  214.         saved = true;
  215.         try {
  216.             BufferedWriter writer = new BufferedWriter(new FileWriter(output));
  217.             writer.append(value);
  218.             writer.close();
  219.         } catch (IOException e) {
  220.             System.out.println("Данные в файл не могут быть записаны! У программы нет доступа к файлу или он занят другим процессом!");
  221.             saved = false;
  222.         }
  223.  
  224.         return saved;
  225.     }
  226. }
Advertisement
Add Comment
Please, Sign In to add comment