Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package dev.rexe;
- import java.io.*;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Scanner;
- public class Main {
- public final static String DEFAULT_INPUT_FILE = "input.txt";
- public final static String DEFAULT_OUTPUT_FILE = "output.txt";
- public final static int PRINT_TYPE_MIN = 0;
- public final static int PRINT_TYPE_MAX = 2;
- public final static int SCAN_TYPE_MIN = 0;
- public final static int SCAN_TYPE_MAX = 1;
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String value, res;
- System.out.println("2. Дана непустая последовательность символов, требуется построить и напечатать множество, элементами которого являются встречающиеся в последовательности знаки арифметических операций и чётные цифры.");
- value = Main.readString(scanner);
- System.out.println(value);
- res = Main.calculate(value);
- Main.printResult(scanner, res);
- scanner.close();
- }
- public static String calculate(String input) {
- HashSet<Character> set = new HashSet<>(List.of('+', '-', '*', '/', '.', ',', '=', '^', '%', '0', '2', '4', '6', '8'));
- StringBuilder calculated = new StringBuilder();
- for (char c : input.toCharArray()) {
- if (set.contains(c))
- calculated.append(c);
- }
- return calculated.toString();
- }
- public static boolean checkFileAvailability(String filePath, boolean read) {
- boolean fl;
- fl = true;
- try {
- File file = new File(filePath);
- if (!read) {
- BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file));
- fileWriter.close();
- } else {
- BufferedReader fileReader = new BufferedReader(new FileReader(file));
- fileReader.close();
- }
- } catch (Exception e) {
- fl = false;
- }
- if (!isTextFile(filePath)) {
- fl = false;
- }
- return fl;
- }
- public static boolean isTextFile(String filePath) {
- boolean isTxt;
- isTxt = (filePath.length() > 4 &&
- filePath.charAt(filePath.length() - 4) == '.' &&
- filePath.charAt(filePath.length() - 3) == 't' &&
- filePath.charAt(filePath.length() - 2) == 'x' &&
- filePath.charAt(filePath.length() - 1) == 't');
- return isTxt;
- }
- public static String readString(Scanner scanner) {
- String value;
- int type;
- System.out.println("\nКак считать значения для поиска решения?");
- System.out.println("0 - Из ввода с клавиатуры (консоль)");
- System.out.println("1 - Из файла");
- type = takeIntValueInRangeFromConsole(scanner, "Выбранный вариант ввода: ", SCAN_TYPE_MIN, SCAN_TYPE_MAX);
- if (type == 1) {
- value = readStringFromFile(scanner);
- } else {
- value = readStringFromConsole(scanner);
- }
- return value;
- }
- public static String takeValueFromFile(BufferedReader reader) {
- boolean isValue;
- StringBuilder value = new StringBuilder();
- isValue = true;
- try {
- while (isValue) {
- int c = reader.read();
- if (c != -1 && c != '\n' && c != ' ') {
- value.append((char) c);
- } else
- isValue = false;
- }
- } catch (IOException e) {}
- return value.toString();
- }
- public static String readStringFromFile(Scanner scanner) {
- String value = "";
- boolean isInCorrect = true;
- while (isInCorrect) {
- File file = takeCorrectFile(scanner, true);
- isInCorrect = false;
- try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
- value = takeValueFromFile(reader);
- } catch (IOException e) {
- isInCorrect = true;
- System.out.println("Этот файл не существует! Введите путь до существующего файла!");
- }
- }
- return value;
- }
- public static String readStringFromConsole(Scanner scanner) {
- String value;
- System.out.print("Строка для решения: ");
- value = scanner.nextLine();
- return value;
- }
- public static int takeIntValueFromConsole(Scanner scanner, String text) {
- boolean isInCorrect;
- int value;
- isInCorrect = true;
- value = 0;
- while (isInCorrect) {
- System.out.print(text);
- try {
- value = Integer.parseInt(scanner.nextLine());
- isInCorrect = false;
- } catch (NumberFormatException e) {
- System.out.println("Введите число, а не строку или что-то иное!");
- }
- }
- return value;
- }
- public static int takeIntValueInRangeFromConsole(Scanner scanner, String text, int min, int max) {
- boolean isInCorrect;
- int value;
- isInCorrect = true;
- value = 0;
- while (isInCorrect) {
- value = takeIntValueFromConsole(scanner, text);
- isInCorrect = false;
- if ((value < min || value > max)) {
- isInCorrect = true;
- System.out.println("Значение должно находится в границах от " + min + " до " + max + "!");
- }
- }
- return value;
- }
- public static void printResult(Scanner scanner, String value) {
- boolean saved;
- int type;
- System.out.println("\nКуда вывести результат решения?");
- System.out.println("0 - Только консоль");
- System.out.println("1 - Только в файл");
- System.out.println("2 - И в файл, и в консоль");
- type = takeIntValueInRangeFromConsole(scanner, "Выбранный вариант вывода: ", PRINT_TYPE_MIN, PRINT_TYPE_MAX);
- saved = false;
- switch (type) {
- case 0 -> {
- System.out.println("\nМножество арифметических знаков и чётных чисел: " + value);
- }
- case 1 -> {
- File output = takeCorrectFile(scanner, false);
- saved = saveResultIntoFile(output, value);
- }
- case 2 -> {
- File output = takeCorrectFile(scanner, false);
- saved = saveResultIntoFile(output, value);
- System.out.println("\nМножество арифметических знаков и чётных чисел: " + value);
- }
- }
- if (saved)
- System.out.println("Результат записан в выходной файл!");
- }
- public static File takeCorrectFile(Scanner scanner, boolean input) {
- boolean isInCorrect;
- String value = "";
- isInCorrect = true;
- while(isInCorrect) {
- if (input)
- System.out.print("Введите путь до входного файла (пустая строка – " + DEFAULT_INPUT_FILE + "): ");
- else
- System.out.print("Введите путь до выходного файла (пустая строка – " + DEFAULT_OUTPUT_FILE + "): ");
- value = scanner.nextLine();
- isInCorrect = false;
- if (value.isEmpty()) {
- if (input)
- value = DEFAULT_INPUT_FILE;
- else
- value = DEFAULT_OUTPUT_FILE;
- }
- if (!checkFileAvailability(value, input)) {
- isInCorrect = true;
- System.out.println("Путь ведёт до файла, который недоступен или который не является текстовым файлом!");
- }
- }
- File result = new File(value);
- return result;
- }
- public static boolean saveResultIntoFile(File output, String value) {
- boolean saved;
- saved = true;
- try {
- BufferedWriter writer = new BufferedWriter(new FileWriter(output));
- writer.append(value);
- writer.close();
- } catch (IOException e) {
- System.out.println("Данные в файл не могут быть записаны! У программы нет доступа к файлу или он занят другим процессом!");
- saved = false;
- }
- return saved;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment