Advertisement
dxvmxnd

Untitled

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