Vanilla_Fury

Untitled

Nov 12th, 2020
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.20 KB | None | 0 0
  1. // В заданном тексте в каждом четном слове заменить все строчные буквенные символы на прописные, а каждое нечетное слово заключить в круглые скобки.
  2.  
  3. package com.company;
  4.  
  5. import java.io.File;
  6. import java.io.PrintWriter;
  7. import java.util.Scanner;
  8.  
  9. class ExceptionFileCannotBeReadOrEmpty extends Exception {
  10. }
  11.  
  12. public class Main {
  13.  
  14. private static Scanner scConsole;
  15.  
  16. private static final String MES_TASK = "В заданном тексте в каждом четном слове заменить все строчные буквенные символы на прописные, а каждое нечетное слово заключить в круглые скобки.";
  17. private static final String ERROR_FILE_NOT_FOUND = "Файл не найден.";
  18. private static final String FORMAT_INPUT_OF_PATH = "Пожалуйста, введите путь к файлу %s: ";
  19. private static final String MES_ASK_INPUT_METHOD = "\nОткуда брать данные?\n\t1 - из файла\n\t2 - ввести вручную\n";
  20. private static final String MES_ASK_AGAIN_INPUT_METHOD = "\t\"1\" - повторить попытку.\n\t\"2\" - ввести данные из консоли.\n";
  21. private static final String ERROR_FILE_CANNOT_BE_READ_OR_IS_EMPTY = "Файл не может быть прочитан или пуст.";
  22. private static final String MES_ASK_OUTPUT_TO_FILE = "Хотите вывести ответ в файл?\n\t1 - да\n\t2 - нет\n";
  23. private static final String ERROR_FILE_CANNOT_BE_CREATED_OT_OPENED = "Файл не может быть создан или открыт. Повторите попытку:\n";
  24. private static final String ERROR_CHOICE_IS_INCORRECT = "\tНадо ввести \"1\" или \"2\".\n\tПовторите попытку: ";
  25.  
  26. private static String choose(String sChoice1, String sChoice2, String sQuestion) {
  27. short nChoice = 2;
  28. boolean bIsIncorrect;
  29. String sAnswer;
  30.  
  31. System.out.println(sQuestion + "\tВаш выбор: ");
  32. do {
  33. bIsIncorrect = false;
  34. try {
  35. nChoice = Short.parseShort(scConsole.nextLine());
  36. } catch (NumberFormatException e) {
  37. bIsIncorrect = true;
  38. }
  39. if (!bIsIncorrect && !(nChoice == 1) && !(nChoice == 2)) {
  40. bIsIncorrect = true;
  41. }
  42. if (bIsIncorrect) {
  43. System.out.println(ERROR_CHOICE_IS_INCORRECT);
  44. }
  45. } while (bIsIncorrect);
  46.  
  47. sAnswer = nChoice == 1 ? sChoice1 : sChoice2;
  48.  
  49. return sAnswer;
  50. }
  51.  
  52. private static String inputPathToFile(boolean isInput) {
  53. String file;
  54.  
  55. String partOfText;
  56. if (isInput) partOfText = "ввода";
  57. else partOfText = "вывода";
  58.  
  59. System.out.printf(FORMAT_INPUT_OF_PATH, partOfText);
  60. file = scConsole.nextLine();
  61. return file;
  62. }
  63.  
  64. private static String readStringFromFile(String sPathToFile) throws java.io.FileNotFoundException, ExceptionFileCannotBeReadOrEmpty {
  65. Scanner scFileInput = new Scanner(new File(sPathToFile));
  66. StringBuilder sInput = new StringBuilder();
  67.  
  68. if (scFileInput.hasNextLine()) {
  69. do {
  70. sInput.append(scFileInput.nextLine()).append("\n");
  71. } while (scFileInput.hasNextLine());
  72. } else {
  73. throw new ExceptionFileCannotBeReadOrEmpty();
  74. }
  75.  
  76. scFileInput.close();
  77.  
  78.  
  79. System.out.println("На входе:\n" + sInput);
  80. return sInput.toString();
  81. }
  82.  
  83. private static String readStringFromConsole() {
  84. String sInput = "";
  85.  
  86. System.out.println("Введите строку:");
  87. sInput = scConsole.nextLine();
  88.  
  89. return sInput;
  90. }
  91.  
  92. private static String getInput() {
  93. String sInput = "";
  94. boolean bInputIsNotDone = true;
  95.  
  96. String sInputMethod = choose("FromFile", "FromConsole", MES_ASK_INPUT_METHOD);
  97.  
  98. do {
  99. switch (sInputMethod) {
  100. case "FromFile" -> {
  101. String sPathToFile = inputPathToFile(true);
  102. try {
  103. sInput = readStringFromFile(sPathToFile);
  104. bInputIsNotDone = false;
  105. } catch (java.io.FileNotFoundException e) {
  106. System.out.println(ERROR_FILE_NOT_FOUND);
  107. } catch (ExceptionFileCannotBeReadOrEmpty e) {
  108. System.out.println(ERROR_FILE_CANNOT_BE_READ_OR_IS_EMPTY);
  109. }
  110. if (bInputIsNotDone) {
  111. sInputMethod = choose("FromFile", "FromConsole", MES_ASK_AGAIN_INPUT_METHOD);
  112. }
  113. }
  114. case "FromConsole" -> {
  115. sInput = readStringFromConsole();
  116. bInputIsNotDone = false;
  117. }
  118. }
  119. } while (bInputIsNotDone);
  120.  
  121. return sInput;
  122. }
  123.  
  124. private static String changeStringToAns(String sInput) {
  125. String sAnswer = "";
  126. Scanner scStringInput = new Scanner(sInput);
  127. Scanner scLine;
  128.  
  129. int i = 1;
  130. while (scStringInput.hasNextLine()) {
  131. scLine = new Scanner(scStringInput.nextLine());
  132. while (scLine.hasNext()) {
  133. sAnswer += i % 2 == 0 ? scLine.next().toUpperCase() + " " : "(" + scLine.next() + ") ";
  134. i++;
  135. }
  136. sAnswer += "\n";
  137. }
  138.  
  139. return sAnswer;
  140. }
  141.  
  142. private static void outputToFile(String sAnswer, String sPathToFIle) {
  143. boolean bOutputNotReady = true;
  144. do {
  145. try {
  146. PrintWriter fOutput = new PrintWriter(sPathToFIle);
  147. fOutput.print(sAnswer);
  148. fOutput.close();
  149. bOutputNotReady = false;
  150. } catch (Exception e) {
  151. System.out.print(ERROR_FILE_CANNOT_BE_CREATED_OT_OPENED);
  152. }
  153. } while (bOutputNotReady);
  154. }
  155.  
  156. private static void outputAnswer(String sAnswer) {
  157. System.out.println("Ответ:\n" + sAnswer);
  158. String sShouldOutputInfoToFile = choose("Output to file", "Don't output to file", MES_ASK_OUTPUT_TO_FILE);
  159. if (sShouldOutputInfoToFile == "Output to file") {
  160. String sPathToFile = inputPathToFile(false);
  161. outputToFile(sAnswer, sPathToFile);
  162. }
  163.  
  164. }
  165.  
  166. public static void main(String[] args) {
  167. scConsole = new Scanner(System.in);
  168.  
  169. System.out.println(MES_TASK);
  170. // Путь к моему файлу ввода: /Users/sasha/Documents/___Университет/ОАиП/Пз/Лабы/блок 3/input.txt
  171. // Путь к моему файлу вывода: /Users/sasha/Documents/___Университет/ОАиП/Пз/Лабы/блок 3/output.txt
  172. String sInput = getInput();
  173. String sAnswer = changeStringToAns(sInput);
  174. outputAnswer(sAnswer);
  175. scConsole.close();
  176. }
  177. }
  178.  
Add Comment
Please, Sign In to add comment