Advertisement
MaksNew

Untitled

Dec 17th, 2022
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.55 KB | None | 0 0
  1. package don23;
  2.  
  3. import java.io.*;
  4. import java.util.Scanner;
  5. import java.util.regex.Matcher;
  6. import java.util.regex.Pattern;
  7.  
  8. public class Main {
  9.  
  10. public static Scanner scan = new Scanner(System.in);
  11.  
  12. static int getMatrixSize()
  13. {
  14. int order = 0;
  15. boolean IsNotCorrect;
  16. do
  17. {
  18. System.out.println("Введите порядок матрицы: ");
  19. IsNotCorrect = false;
  20. try
  21. {
  22. order = Integer.parseInt(scan.nextLine());
  23. }
  24. catch (Exception e)
  25. {
  26. IsNotCorrect = true;
  27. System.out.println("Порядок матрицы должен быть положительным числом.");
  28. }
  29. if (!IsNotCorrect && (((order < 1) || (order > 10000))))
  30. {
  31. System.out.println("Порядок матрицы должен принадлежать промежутку от 1 до 10000");
  32. IsNotCorrect = true;
  33. }
  34. } while (IsNotCorrect);
  35. return order;
  36. }
  37.  
  38. static int getMatrixElement()
  39. {
  40. int element = 0;
  41. boolean IsNotCorrect;
  42. do
  43. {
  44. System.out.println("Введите элемент матрицы: ");
  45. IsNotCorrect = false;
  46. try
  47. {
  48. element = Integer.parseInt(scan.nextLine());
  49. }
  50. catch (Exception e)
  51. {
  52. IsNotCorrect = true;
  53. System.out.println("Элемент матрицы должен быть положительным числом.");
  54. }
  55. if (!IsNotCorrect && (((element < -2147000000) || (element > 2147000000))))
  56. {
  57. System.out.println("Элемент матрицы должен принадлежать промежутку от -2147000000 до 2147000000");
  58. IsNotCorrect = true;
  59. }
  60. } while (IsNotCorrect);
  61. return element;
  62. }
  63.  
  64. static int[][] сreateMatrix(int order)
  65. {
  66. var matrix = new int[order][order];
  67. for (int i = 0; i < order; i++) {
  68. for (int j = 0; j < order; j++)
  69. matrix[i][j] = getMatrixElement();
  70. }
  71. return matrix;
  72. }
  73.  
  74. static int calculateSumByCondition(int[][] matrix)
  75. {
  76. int sum = 0;
  77. int j = 0;
  78. for (int i = 0; i < matrix.length; i++)
  79. {
  80. j = 0;
  81. while ((j < matrix.length) && (i != j))
  82. {
  83. if (matrix[i][j] > 0)
  84. sum += matrix[i][j];
  85. j++;
  86. }
  87. }
  88. return sum;
  89. }
  90.  
  91. static void printMatrix(int[][] matrix) {
  92. for (int i = 0; i < matrix.length; i++) {
  93. for (int j = 0; j < matrix.length; j++) {
  94. System.out.printf("%6d", matrix[i][j]);
  95. }
  96. System.out.println();
  97. }
  98. System.out.println();
  99. }
  100.  
  101. static String getOutputDirectory()
  102. {
  103. String patho;
  104. boolean isIncorrect;
  105. isIncorrect = true;
  106. do
  107. {
  108. System.out.println("Введите директорию, в которую хотите сохранить результат:");
  109. patho = scan.nextLine();
  110. var file = new File(patho);
  111.  
  112. if (file.exists())
  113. isIncorrect = false;
  114. else
  115. System.out.println("Такой директории не существует. Попробуйте ещё раз.");
  116. } while (isIncorrect);
  117. return patho;
  118. }
  119.  
  120. static void printResultToFile(int[][] matrix, int sum) throws IOException {
  121. var patho = getOutputDirectory();
  122. FileWriter myWriter = new FileWriter(patho + "output.txt");
  123. myWriter.write("Для матрицы\n");
  124. for (int i = 0; i < matrix.length; i++)
  125. {
  126. for (int j = 0; j < matrix.length; j++)
  127. myWriter.write(String.format("%6d", matrix[i][j]));
  128. myWriter.write("\n");
  129. }
  130. myWriter.write("Сумма положительных элементов под главной диагональю = " + sum);
  131. myWriter.close();
  132. System.out.println("Ответ сохранен по указанному пути.");
  133. }
  134.  
  135. static void workWithConsole() throws IOException {
  136. int size = getMatrixSize();
  137. var matrix = сreateMatrix(size);
  138. printMatrix(matrix);
  139. int sum = calculateSumByCondition(matrix);
  140. System.out.println("Сумма положительных элементов под главной диагональю: " + sum);
  141. printResultToFile(matrix, sum);
  142. }
  143.  
  144. static boolean isFileCorrect(String path) throws IOException {
  145. int num = 0;
  146. int totalCount = 0;
  147. boolean isCorrect;
  148. FileReader reader = new FileReader(path);
  149. Scanner scanner = new Scanner(reader);
  150. isCorrect = true;
  151. try
  152. {
  153. var size = scanner.nextInt();
  154. scanner.nextLine();
  155. while (scanner.hasNextLine() && isCorrect) {
  156. Matcher matcher = Pattern.compile("\\d+").matcher(scanner.nextLine());
  157. int iCount = 0;
  158. while (matcher.find()) {
  159. iCount++;
  160. totalCount++;
  161. }
  162. if (iCount != size && totalCount != size * size) {
  163. isCorrect = false;
  164. }
  165. }
  166. }
  167. catch(Exception e)
  168. {
  169. isCorrect = false;
  170. }
  171. reader.close();
  172. return isCorrect;
  173. }
  174.  
  175. static String getMatrixFilePath() throws IOException {
  176. String path;
  177. boolean isIncorrect = true;
  178. do
  179. {
  180. System.out.println("Введите абсолютный путь к файлу: ");
  181. path = scan.nextLine();
  182. var mf = new File(path);
  183. if (!mf.exists())
  184. {
  185. System.out.println("Файл не найден. Проверьте введённый путь.");
  186. }
  187. else
  188. {
  189. if (isFileCorrect(path))
  190. isIncorrect = false;
  191. else
  192. System.out.println("Проверьте данные в файле. Это должны быть числа, записанные в виде матрицы. Порядок матрицы должен соответствовать введённому.");
  193. }
  194. } while (isIncorrect);
  195. return path;
  196. }
  197.  
  198. static int[][] createMatrixFromFile(String path) throws FileNotFoundException {
  199. FileReader matrixFile = new FileReader(path);
  200. Scanner sc = new Scanner (matrixFile);
  201. var order = sc.nextInt();
  202. var matrix = new int[order][order];
  203. for (int i = 0; i < order; i++)
  204. for (int j = 0; j < order; j++)
  205. matrix[i][j] = sc.nextInt();
  206. return matrix;
  207. }
  208.  
  209. static void workWithFile() throws IOException {
  210. var matrix = createMatrixFromFile(getMatrixFilePath());
  211. printMatrix(matrix);
  212. int sum = calculateSumByCondition(matrix);
  213. System.out.println("Сумма положительных элементов под главной диагональю: " + sum);
  214. printResultToFile(matrix, sum);
  215. }
  216.  
  217. static void setProgramWorkType() throws IOException {
  218. int answer = 0;
  219. boolean isNotCorrect;
  220. do
  221. {
  222. System.out.println("1 - работать с консолью, 2 - с файлом: ");
  223. isNotCorrect = false;
  224. try
  225. {
  226. answer = Integer.parseInt(scan.nextLine());
  227. }
  228. catch (Exception e)
  229. {
  230. isNotCorrect = true;
  231. System.out.println("Введите число!");
  232. }
  233. if (!isNotCorrect && (((answer < 1) || (answer > 2))))
  234. {
  235. System.out.println("Выбирете один из предложенных вариантов!");
  236. isNotCorrect = true;
  237. }
  238. } while (isNotCorrect);
  239. if (answer == 1)
  240. workWithConsole();
  241. else
  242. workWithFile();
  243. }
  244.  
  245. public static void main(String[] args) throws IOException {
  246. setProgramWorkType();
  247. }
  248. }
  249.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement