Advertisement
dxvmxnd

Untitled

Dec 19th, 2024
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.19 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.Scanner;
  3.  
  4. public class Main {
  5. public static void main(String[] args) {
  6. String str;
  7. String answerStr;
  8. int numOfWord;
  9.  
  10. outputTask();
  11. str = choiceOfInput();
  12. answerStr = findForShortestWord(str);
  13. numOfWord = findNumInWord(str, answerStr);
  14. outputAnswer(answerStr, numOfWord);
  15.  
  16. }
  17. public static int findNumInWord(String str, String answerStr) {
  18. int strLength = str.length();
  19. int answerLength = answerStr.length();
  20. int num;
  21.  
  22. num = 0;
  23.  
  24. for (int i = 0; i <= strLength - answerLength; i++) {
  25. int j = 0;
  26. while (j < answerLength && str.charAt(i + j) == answerStr.charAt(j)) {
  27. j++;
  28. }
  29. if (j == answerLength) {
  30. num = i;
  31. }
  32. }
  33. return num;
  34. }
  35. private static final Scanner scanner = new Scanner(System.in);
  36. public static String findForShortestWord(String str) {
  37. String shortestWord = "";
  38. String currentWord = "";
  39. boolean isFirstWord = true;
  40.  
  41. for (int i = 0; i < str.length(); i++) {
  42. char ch = str.charAt(i);
  43. if (ch == ' ') {
  44. if (!currentWord.isEmpty()) {
  45. if (isFirstWord || currentWord.length() < shortestWord.length()) {
  46. shortestWord = currentWord;
  47. isFirstWord = false;
  48. }
  49. currentWord = "";
  50. }
  51. } else {
  52. currentWord += ch;
  53. }
  54. }
  55.  
  56. if (!currentWord.isEmpty() && (isFirstWord || currentWord.length() < shortestWord.length())) {
  57. shortestWord = currentWord;
  58. }
  59. return shortestWord;
  60. }
  61. public static void outputAnswer(String str, int num){
  62. String path;
  63. boolean isIncorrect;
  64.  
  65. System.out.println("\nСамое короткое слово в предложении: " + str);
  66. System.out.println("\nОно начинается с позиции: " + num);
  67.  
  68.  
  69. path = outputPath();
  70. do {
  71. isIncorrect = false;
  72. try (FileWriter writer = new FileWriter(path, true)) {
  73. writer.write("\nСамое короткое слово в предложении: " + str);
  74. writer.write("\nОно начинается с позиции: " + Integer.toString(num));
  75. } catch (IOException ioException) {
  76. System.err.println("Ошибка при записи в файл");
  77. isIncorrect = true;
  78. }
  79. } while (isIncorrect);
  80. System.out.println("Данные записаны в файл.");
  81. }
  82. public static String outputPath() {
  83. String path;
  84. boolean isIncorrect;
  85.  
  86. do {
  87. isIncorrect = false;
  88. System.out.println("Введите путь к файлу для вывода: ");
  89. System.out.println();
  90. path = scanner.nextLine();
  91.  
  92. File file = new File(path);
  93. if (!file.exists()) {
  94. System.out.println("По указанном пути файл не найден.");
  95. isIncorrect = true;
  96. } else if (!getExtension(path).equals("txt")) {
  97. System.err.println("Ошибка, неправильный тип файла!");
  98. isIncorrect = true;
  99. }
  100. } while (isIncorrect);
  101. return path;
  102. }
  103. public static void outputTask() {
  104. System.out.println("Данная программа ищет в заданном тексте самое короткое слово.");
  105. }
  106. public static String getExtension(String path) {
  107. int pos = path.lastIndexOf('.');
  108. if (pos <= 0) {
  109. return "";
  110. }
  111. return path.substring(pos + 1);
  112. }
  113. public static String choicePath() {
  114. String path;
  115. boolean isIncorrect;
  116.  
  117. do {
  118. isIncorrect = false;
  119. System.out.println("Введите путь к файлу: ");
  120. path = scanner.nextLine();
  121.  
  122. File file = new File(path);
  123. if (!file.exists()) {
  124. System.out.println("По указанном пути файл не найден.");
  125. isIncorrect = true;
  126. } else if (!getExtension(path).equals("txt")) {
  127. System.err.println("Ошибка, неправильный тип файла!");
  128. isIncorrect = true;
  129. }
  130. } while (isIncorrect);
  131. return path;
  132.  
  133. }
  134. public static String inputStrFromFile(String path) {
  135. boolean isNotCorrect;
  136. String str = "";
  137. System.out.println("Считывание строки...");
  138.  
  139. try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
  140. str = reader.readLine();
  141.  
  142. if (str.isEmpty()) {
  143. System.out.println("Ошибка ввода! Строка должна иметь хотя бы 1 символ! Введите строку с клавиатуры.");
  144. str = inputFromConsole();
  145. }
  146. else {
  147. System.out.println("Строка для перекодирования: " + str);
  148. }
  149. } catch (IOException ioException) {
  150. isNotCorrect = true;
  151. }
  152.  
  153. return str;
  154. }
  155. public static String inputFromFile() {
  156. String path;
  157. String str;
  158.  
  159. path = choicePath();
  160. str = inputStrFromFile(path);
  161.  
  162.  
  163. return str;
  164. }
  165. public static String inputFromConsole() {
  166. String str;
  167. boolean isNotCorrect;
  168.  
  169. do {
  170. isNotCorrect = false;
  171. System.out.println("Введите предложение: ");
  172. str = scanner.nextLine();
  173. if ((str.length() < 1) || ((str.charAt(0) == ' ') && (str.length() > 0))) {
  174. isNotCorrect = true;
  175. System.out.println("Текст должен содержать минимум 1 символ!");
  176. }
  177. } while (isNotCorrect);
  178.  
  179. return str;
  180.  
  181. }
  182. public static String choiceOfInput() {
  183. String str;
  184. int choice;
  185. boolean isNotCorrect;
  186.  
  187. choice = -1;
  188. do {
  189. isNotCorrect = false;
  190. System.out.println("Выберите, откуда вводить данные. Введите 0, если с консоли; 1, если с файла");
  191. try {
  192. choice = Integer.parseInt(scanner.nextLine());
  193. } catch (NumberFormatException exception) {
  194. isNotCorrect = true;
  195. }
  196. if (isNotCorrect || ((choice != 0) && (choice != 1))) {
  197. isNotCorrect = true;
  198. System.err.println("Неверный ввод данных!");
  199. }
  200. } while (isNotCorrect);
  201.  
  202. if (choice == 0) {
  203. str = inputFromConsole();
  204. }
  205. else {
  206. str = inputFromFile();
  207. }
  208.  
  209. return str;
  210. }
  211. }
  212.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement