ValeriaAVR

Java23

Oct 28th, 2024
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.67 KB | None | 0 0
  1. import java.io.*;
  2. import java.nio.file.*;
  3. import java.util.Scanner;
  4. public class Main {
  5.     final static int MIN_N = 2;
  6.     final static int MAX_N = 100;
  7.     final static int MIN_A = -10000;
  8.     final static int MAX_A = 10000;
  9.     static Scanner in = new Scanner(System.in);
  10.  
  11.     public static int inputAndCheckChoice() {
  12.         boolean isIncorrect;
  13.         isIncorrect = false;
  14.         int choice;
  15.         choice = 0;
  16.         do {
  17.             System.out.println("Введите ваш выбор.");
  18.             try {
  19.                 choice = Integer.parseInt(in.nextLine());
  20.             } catch (NumberFormatException e) {
  21.                 isIncorrect = true;
  22.                 System.err.println("Некорректный ввод.");
  23.             }
  24.             if (choice != 1 && choice != 2) {
  25.                 System.err.println("Введите 1 или 2.");
  26.             } else {
  27.                 isIncorrect = false;
  28.             }
  29.         } while (isIncorrect);
  30.         return choice;
  31.     }
  32.  
  33.     public static int inputAndCheckN() {
  34.         boolean isIncorrect;
  35.         int n;
  36.         n = 0;
  37.         do {
  38.             isIncorrect = false;
  39.             System.out.println("Введите порядок матрицы n: ");
  40.             try {
  41.                 n = Integer.parseInt(in.nextLine());
  42.             } catch (NumberFormatException e) {
  43.                 isIncorrect = true;
  44.                 System.err.println("Некорректный ввод. Введите целое число.");
  45.             }
  46.             if (!isIncorrect && (n < MIN_N || n > MAX_N)) {
  47.                 isIncorrect = true;
  48.                 System.err.println("Диапазон значений n от " + MIN_N + " до " + MAX_N + ".");
  49.             }
  50.         } while (isIncorrect);
  51.         return n;
  52.     }
  53.  
  54.     public static boolean isEof(final String fileName) {
  55.         boolean isEof;
  56.         isEof = false;
  57.         try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
  58.             String line = br.readLine();
  59.             if (line != null) {
  60.                 isEof = true;
  61.             }
  62.         } catch (IOException e) {
  63.             System.err.println("Ошибка.");
  64.         }
  65.         return isEof;
  66.     }
  67.  
  68.     public static String requestFileNameForReading() {
  69.         boolean isIncorrect;
  70.         String fileName;
  71.         isIncorrect = true;
  72.         File tempFile;
  73.         Path path;
  74.         do {
  75.             System.out.println("Введите относительный путь к файлу.");
  76.             fileName = in.nextLine();
  77.             path = Paths.get(fileName);
  78.             tempFile = new File(fileName);
  79.             if (!tempFile.exists()) {
  80.                 System.err.println("Файл не существует.");
  81.             } else if (fileName.length() < 5 || !fileName.endsWith(".txt")) {
  82.                 System.err.println("Файл не является текстовым.");
  83.             } else if (!Files.isReadable(path)) {
  84.                 System.err.println("Этот файл невозможно открыть для чтения.");
  85.             } else if (!isEof(fileName)) {
  86.                 System.err.println("Этот файл пустой.");
  87.             } else {
  88.                 isIncorrect = false;
  89.             }
  90.         } while (isIncorrect);
  91.         return fileName;
  92.     }
  93.  
  94.     public static String requestFileNameForWriting() {
  95.         boolean isIncorrect;
  96.         String fileName;
  97.         isIncorrect = true;
  98.         File tempFile;
  99.         Path path;
  100.         do {
  101.             System.out.println("Введите относительный путь к файлу.");
  102.             fileName = in.nextLine();
  103.             path = Paths.get(fileName);
  104.             tempFile = new File(fileName);
  105.             if (!tempFile.exists()) {
  106.                 System.err.println("Файл не существует.");
  107.             } else if (fileName.length() < 5 || !fileName.endsWith(".txt")) {
  108.                 System.err.println("Файл не является текстовым.");
  109.             } else if (!Files.isWritable(path)) {
  110.                 System.err.println("Этот файл невозможно открыть для записи.");
  111.             } else {
  112.                 isIncorrect = false;
  113.             }
  114.         } while (isIncorrect);
  115.         return fileName;
  116.     }
  117.  
  118.     public static int inputSizeFromFile(String fileName) {
  119.         boolean isIncorrect;
  120.         int size;
  121.         isIncorrect = false;
  122.         do {
  123.             size = 0;
  124.             try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
  125.                 String line = br.readLine();
  126.                 if (line != null) {
  127.                     size = Integer.parseInt(line.trim());
  128.                     isIncorrect = (size < MIN_N) || (size > MAX_N);
  129.                     if (isIncorrect) {
  130.                         System.out.println("Размер не входит в диапазон от " + MIN_N + " до " + MAX_N);
  131.                         isIncorrect = false;
  132.                         fileName = requestFileNameForReading();
  133.                     }
  134.                 } else {
  135.                     System.out.println("Файл пуст.");
  136.                     isIncorrect = true;
  137.                     fileName = requestFileNameForReading();
  138.                 }
  139.             } catch (IOException e) {
  140.                 System.out.println("Ошибка при чтении файла: ");
  141.                 isIncorrect = true;
  142.                 fileName = requestFileNameForReading();
  143.             } catch (NumberFormatException e) {
  144.                 System.out.println("Ошибка в первой строке. Неправильный размер матрицы");
  145.                 isIncorrect = true;
  146.                 fileName = requestFileNameForReading();
  147.             }
  148.         } while (isIncorrect);
  149.         return size;
  150.     }
  151.  
  152.     public static double[][] readMatrix(int size, String fileName) {
  153.         double[][] matrix = new double[size][size];
  154.         boolean isIncorrect;
  155.         String[] doubleInString;
  156.         String tempLine;
  157.         do {
  158.             isIncorrect = false;
  159.             try (BufferedReader fReader = new BufferedReader(new FileReader(fileName))) {
  160.                 fReader.readLine();
  161.                 if (matrix != null) {
  162.                     for (int i = 0; i < size; i++) {
  163.                         tempLine = fReader.readLine();
  164.                         if (tempLine != null) {
  165.                             doubleInString = tempLine.split(" ");
  166.                             for (int j = 0; j < size; j++) {
  167.                                 matrix[i][j] = Double.parseDouble(doubleInString[j]);
  168.                                 if (matrix[i][j] < MIN_A || matrix[i][j] > MAX_A) {
  169.                                     isIncorrect = true;
  170.                                 }
  171.                             }
  172.                         }
  173.                     }
  174.                     if (isIncorrect) {
  175.                         System.err.println("Элементы матрицы выходят за диапазон допустимых значений.");
  176.                     }
  177.                 } else {
  178.                     System.err.println("Матрица не содержит элементов.");
  179.                     isIncorrect = true;
  180.                 }
  181.             } catch (NumberFormatException e) {
  182.                 System.err.println("Некорректный тип данных.");
  183.                 isIncorrect = true;
  184.                 matrix = null;
  185.             } catch (IOException e) {
  186.                 System.err.println("Непредвиденная ошибка.");
  187.                 isIncorrect = true;
  188.                 matrix = null;
  189.             }
  190.             if (isIncorrect) {
  191.                 fileName = requestFileNameForReading();
  192.                 size = inputSizeFromFile(fileName);
  193.             }
  194.         } while (isIncorrect);
  195.         return matrix;
  196.     }
  197.  
  198.     public static double[][] createMatrix(final int n) {
  199.         double[][] matrix = new double[n][n];
  200.         boolean isIncorrect;
  201.         for (int i = 0; i < n; i++) {
  202.             for (int j = 0; j < n; j++) {
  203.                 do {
  204.                     isIncorrect = false;
  205.                     System.out.println("Введите элемент матрицы: ");
  206.                     try {
  207.                         matrix[i][j] = Double.parseDouble(in.nextLine());
  208.                     } catch (NumberFormatException e) {
  209.                         isIncorrect = true;
  210.                         System.err.println("Некорректный ввод. Введите число.");
  211.                     }
  212.                     if (!isIncorrect && (matrix[i][j] < MIN_A || matrix[i][j] > MAX_A)) {
  213.                         isIncorrect = true;
  214.                         System.err.println("Диапазон значений A от " + MIN_A + " до " + MAX_A + ".");
  215.                     }
  216.                 } while (isIncorrect);
  217.             }
  218.         }
  219.         return matrix;
  220.     }
  221.  
  222.     public static double sumElements(double[][] matrix, int n) {
  223.         double sum;
  224.         sum = 0.0;
  225.         for (int i = 1; i < n; i++) {
  226.             for (int j = 0; j < i; j++) {
  227.                 if (matrix[i][j] > 0) {
  228.                     sum += matrix[i][j];
  229.                 }
  230.             }
  231.         }
  232.         return sum;
  233.     }
  234.     public static void printToConsole(final double sum) {
  235.         System.out.println("Сумма равна " + sum);
  236.     }
  237.  
  238.     public static boolean printToFile(String fileName, final double sum) {
  239.         boolean isIncorrect;
  240.         isIncorrect = false;
  241.         String result = Double.toString(sum);
  242.         do {
  243.             try (BufferedWriter fWriter = new BufferedWriter(new FileWriter(fileName))) {
  244.                 fWriter.write(result);
  245.                 System.out.println("Результат выведен в файле.");
  246.             } catch (IOException e) {
  247.                 System.err.println("Непредвиденная ошибка.");
  248.                 isIncorrect = true;
  249.                 fileName = requestFileNameForReading();
  250.             }
  251.         } while (isIncorrect);
  252.         return isIncorrect;
  253.     }
  254.  
  255.     public static void main(String[] args) {
  256.         int choice;
  257.         int n;
  258.         double sum;
  259.         boolean isIncorrect;
  260.         String fileName;
  261.         System.out.println("Данная программа считает сумму положительных элементов матрицы порядка n, стоящих под главной диагональю.\nДиапазон значений порядка матрицы n: "
  262.                 + MIN_N + "..." + MAX_N + "\nДиапазон для значений элементов матрицы : " + MIN_A + "..." +
  263.                 MAX_A + "\nОткуда вы хотите вводить данные ? \n1 - консоль, 2 - файл.");
  264.         choice = inputAndCheckChoice();
  265.         double[][] matrix;
  266.         if (choice == 1) {
  267.             n = inputAndCheckN();
  268.             matrix = createMatrix(n);
  269.         } else {
  270.             fileName = requestFileNameForReading();
  271.             n = inputSizeFromFile(fileName);
  272.             matrix = readMatrix(n, fileName);
  273.         }
  274.         sum = sumElements(matrix, n);
  275.         System.out.println("Куда Вы хотите вывести результат? \n1 - консоль, 2 - файл.");
  276.         choice = inputAndCheckChoice();
  277.         if (choice == 1) {
  278.            printToConsole(sum);
  279.         } else {
  280.             do {
  281.                 fileName = requestFileNameForWriting();
  282.                 isIncorrect = printToFile(fileName, sum);
  283.             } while (isIncorrect);
  284.         }
  285.         in.close();
  286.     }
  287. }
  288.  
Advertisement
Add Comment
Please, Sign In to add comment