Advertisement
dxvmxnd

java_1

Dec 17th, 2024 (edited)
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.90 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.Scanner;
  3. public class Main {
  4. private static final Scanner scanner = new Scanner(System.in);
  5. public static void main(String[] args) {
  6. int[] array;
  7. int[] sortedArray;
  8. outputTaskEssence();
  9. array = sourceChoice();
  10. sortedArray = sorting(array);
  11. output(sortedArray);
  12. scanner.close();
  13. }
  14. public static void outputTaskEssence() {
  15. System.out.println("Данная программа сортирует массив методом подсчета.");
  16. }
  17. public static int[] sourceChoice() {
  18. int choiceNumber;
  19. boolean isIncorrect;
  20. int[] array = new int[0];
  21. choiceNumber = -1;
  22. System.out.println("Выберите, откуда будут вводиться данные: ");
  23. do {
  24. isIncorrect = false;
  25. System.out.println("Введите 0, если с консоли; 1, если с файла");
  26. try {
  27. choiceNumber = Integer.parseInt(scanner.nextLine());
  28. } catch (NumberFormatException exception) {
  29. isIncorrect = true;
  30. System.err.println("Неверный ввод данных!");
  31. }
  32. if (((choiceNumber != 0) && (choiceNumber != 1)) || (isIncorrect)) {
  33. isIncorrect = true;
  34. System.err.println("Число должно быть или 0, или 1");
  35. }
  36. } while (isIncorrect);
  37. if (choiceNumber == 0) {
  38. array = inputFromConsole();
  39. } else {
  40. array = inputFromFile();
  41. }
  42. return array;
  43. }
  44. public static int[] inputFromFile() {
  45. String path;
  46. int size;
  47. int[] array;
  48. System.out.println("При записи данных из файла, учтите, что на первой строке написано количество элементов массива, на второй - элементы массива через пробел.");
  49. path = pathChoice();
  50. size = inputSizeFromFile(path);
  51. array = new int[size];
  52. array = readArrayFromFile(path, size, array);
  53. return array;
  54. }
  55. public static String pathChoice() {
  56. String path;
  57. boolean isIncorrect;
  58. do {
  59. isIncorrect = false;
  60. System.out.println("Введите путь к файлу: ");
  61. path = scanner.nextLine();
  62. File file = new File(path);
  63. if (!file.exists()) {
  64. System.out.println("По указанном пути файл не найден.");
  65. isIncorrect = true;
  66. } else if (!getExtension(path).equals("txt")) {
  67. System.err.println("Ошибка, неправильный тип файла!");
  68. isIncorrect = true;
  69. }
  70. } while (isIncorrect);
  71. return path;
  72. }
  73. public static String getExtension(String path) {
  74. int pos = path.lastIndexOf('.');
  75. if (pos <= 0) {
  76. return "";
  77. }
  78. return path.substring(pos + 1);
  79. }
  80. public static int inputSizeFromFile(String path) {
  81. int size;
  82. boolean isIncorrect;
  83. System.out.println("Считывание размера массива...");
  84. size = 0;
  85. isIncorrect = false;
  86. try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
  87. try {
  88. size = Integer.parseInt(reader.readLine());
  89. } catch (NumberFormatException exception) {
  90. if ((size < 1) || (isIncorrect)) {
  91. isIncorrect = true;
  92. System.err.println("Неверный ввод данных! Введите данные с клавиатуры.");
  93. size = inputSizeFromConsole();
  94. }
  95. else {
  96. System.out.println(size);
  97. }
  98. }
  99. } catch (IOException ioException) {
  100. isIncorrect = true;
  101. }
  102. return size;
  103. }
  104. public static int[] readArrayFromFile(String path, int size, int[] array) {
  105. System.out.println("Считывание массива...");
  106. boolean isIncorrect;
  107.  
  108. try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
  109. reader.readLine();
  110. String[] elements = reader.readLine().split(" ");
  111. for (int i = 0; i < size; i++) {
  112. isIncorrect = false;
  113. try {
  114. array[i] = Integer.parseInt(elements[i]);
  115. } catch (NumberFormatException exception) {
  116. isIncorrect = true;
  117. }
  118. if (isIncorrect || (array[i] < 0) || (array[i] > 1000)) {
  119. System.out.println("Неверный ввод данных! Введите данные с клавиатуры.");
  120. array[i] = exceptionRead(i);
  121. }
  122. }
  123. } catch (IOException ioException) {
  124. System.err.println("Ошибка!");
  125. }
  126. return array;
  127. }
  128. public static void output(int[] array) {
  129. String path;
  130. boolean isIncorrect;
  131. System.out.println("\nМассив, отсортированный методом подсчета: ");
  132. for (int i = 0; i < array.length; i++) {
  133. System.out.print(array[i] + " ");
  134. }
  135. path = outputPath();
  136. do {
  137. isIncorrect = false;
  138. try (FileWriter writer = new FileWriter(path, true)) {
  139. writer.write("Массив, отсортированный методом подсчета: \n");
  140. for (int i = 0; i < array.length; i++) {
  141. writer.write(array[i] + " ");
  142. }
  143. } catch (IOException ioException) {
  144. System.err.println("Ошибка при записи в файл");
  145. isIncorrect = true;
  146. }
  147. } while (isIncorrect);
  148. System.out.println("Данные записаны в файл.");
  149. }
  150. public static int[] sorting(int[] arr) {
  151. int maxValue = arr[0];
  152. for (int i = 1; i < arr.length; i++) {
  153. if (arr[i] > maxValue) {
  154. maxValue = arr[i];
  155. }
  156. }
  157.  
  158. int[] count = new int[maxValue + 1];
  159.  
  160. for (int num : arr) {
  161. count[num]++;
  162. }
  163.  
  164. int index = 0;
  165. for (int i = 0; i <= maxValue; i++) {
  166. while (count[i] > 0) {
  167. arr[index++] = i;
  168. count[i]--;
  169. }
  170. }
  171.  
  172. return arr;
  173. }
  174. public static String outputPath() {
  175. String path;
  176. boolean isIncorrect;
  177. do {
  178. isIncorrect = false;
  179. System.out.println("\nВведите путь к файлу для вывода: ");
  180. System.out.println();
  181. path = scanner.nextLine();
  182. File file = new File(path);
  183. if (!file.exists()) {
  184. System.out.println("По указанном пути файл не найден.");
  185. isIncorrect = true;
  186. } else if (!getExtension(path).equals("txt")) {
  187. System.err.println("Ошибка, неправильный тип файла!");
  188. isIncorrect = true;
  189. }
  190. } while (isIncorrect);
  191. return path;
  192. }
  193. public static int[] inputFromConsole() {
  194. int size;
  195. int[] array;
  196. size = inputSizeFromConsole();
  197. array = new int[size];
  198. array = readArrayFromConsole(size, array);
  199. return array;
  200. }
  201. public static int inputSizeFromConsole() {
  202. boolean isIncorrect;
  203. int size;
  204. size = 0;
  205. do {
  206. isIncorrect = false;
  207. System.out.print("Введите количество элементов массива: ");
  208. try {
  209. size = Integer.parseInt(scanner.nextLine());
  210. if (!isIncorrect && (size < 1)) {
  211. System.err.println("Неверный ввод данных!");
  212. isIncorrect = true;
  213. }
  214. } catch (NumberFormatException exception) {
  215. System.err.println("Неверный ввод данных!");
  216. isIncorrect = true;
  217. }
  218. } while (isIncorrect);
  219. return size;
  220. }
  221. public static int[] readArrayFromConsole(int size, int[] array) {
  222. boolean isIncorrect;
  223. for (int i = 0; i < size; i++) {
  224. do {
  225. isIncorrect = false;
  226. System.out.print("Введите " + (i+1) + " элемент массива: ");
  227. try {
  228. array[i] = Integer.parseInt(scanner.nextLine());
  229. } catch (NumberFormatException exception) {
  230. isIncorrect = true;
  231. }
  232. if (isIncorrect || (array[i] < 0) || array[i] > 1000) {
  233. isIncorrect = true;
  234. System.err.println("Неверный ввод данных!");
  235. }
  236. } while (isIncorrect);
  237. }
  238. return array;
  239. }
  240. public static int exceptionRead(int i) {
  241. boolean isIncorrect;
  242. int number;
  243. number = 0;
  244. do {
  245. isIncorrect = false;
  246. System.out.print("Введите " + (i+1) + " элемент массива: ");
  247. try {
  248. number = Integer.parseInt(scanner.nextLine());
  249. } catch (NumberFormatException exception) {
  250. System.err.println("Неверный ввод данных!");
  251. isIncorrect = true;
  252. }
  253. } while (isIncorrect);
  254. return number;
  255. }
  256. }
  257.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement