Advertisement
believe_me

Untitled

Oct 28th, 2021
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.91 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.Scanner;
  3.  
  4. public class lab23 {
  5.  
  6.     static Scanner consoleScanner = new Scanner(System.in);
  7.  
  8.     public static void main(String[] args)
  9.     {
  10.             int userWay, numberOfLines, numberOfColumns, numberOfSortedLines;
  11.             System.out.println("Программа считает количество строк данной матрицы, которые упорядочены по возрастанию.\n");
  12.             userWay = chooseWayOfInput();
  13.             int[][] matrix = receiveMatrix(userWay);
  14.             numberOfLines = matrix.length;
  15.             numberOfColumns = matrix[0].length;
  16.             numberOfSortedLines = counterOfSortedLines(matrix, numberOfLines, numberOfColumns);
  17.             resultOutput(numberOfSortedLines);
  18.             userWayOfOutput(numberOfSortedLines);
  19.             consoleScanner.close();
  20.             System.out.println("Программа завершена");
  21.     }
  22.  
  23.     public static int inputNumber(int minNumber, int maxNumber) {
  24.         Scanner consoleScanner = new Scanner(System.in);
  25.         boolean isIncorrect;
  26.         int number = 0;
  27.         do {
  28.             isIncorrect = false;
  29.             try {
  30.                 number = Integer.parseInt(consoleScanner.nextLine());
  31.             } catch (Exception ex) {
  32.                 System.out.println("Число должно быть целым.");
  33.                 isIncorrect = true;
  34.             }
  35.             if (!isIncorrect && (number < minNumber || number > maxNumber)) {
  36.                 System.out.println("Число должно быть не меньше " + minNumber + " и не больше, чем " + maxNumber);
  37.                 isIncorrect = true;
  38.             }
  39.         } while (isIncorrect);
  40.         return number;
  41.     }
  42.  
  43.     static int chooseWayOfInput() {
  44.         int userWay;
  45.         do {
  46.             System.out.println("Выберите способ ввода: \nНажмите '1', если хотите ввести матрицу через консоль.\nНажмите '2', если хотите считать матрицу из файла.");
  47.             userWay = inputNumber(1, 2);
  48.         } while (userWay != 1 && userWay != 2);
  49.         return userWay;
  50.     }
  51.  
  52.     static String inputPathToFile() {
  53.         System.out.println("Введите путь к файлу:");
  54.         boolean isIncorrect, isCorrect;
  55.         String path;
  56.         do {
  57.             do {
  58.                 isIncorrect = false;
  59.                 path = consoleScanner.nextLine();
  60.                 try {
  61.                     new FileReader(path);
  62.                 } catch (FileNotFoundException e) {
  63.                     System.out.println("Файл не найден. Введите путь к файлу еще раз:");
  64.                     isIncorrect = true;
  65.                 }
  66.             } while (isIncorrect);
  67.             isCorrect = checkExtension(path);
  68.         }while(!isCorrect);
  69.         return path;
  70.     }
  71.  
  72.     static int[][] receiveMatrixFromFile(String path) {
  73.         File file = new File(path);
  74.         int numberOfLines = 0;
  75.         int numberOfColumns = 0;
  76.         int[][] matrix = null;
  77.         boolean isIncorrect;
  78.         do {
  79.             isIncorrect = false;
  80.             try {
  81.                 Scanner fileScanner = new Scanner(file);
  82.                 numberOfLines = fileScanner.nextInt();
  83.                 numberOfColumns = fileScanner.nextInt();
  84.                 matrix = new int[numberOfLines][numberOfColumns];
  85.                 for (int i = 0; i < numberOfLines; i++) {
  86.                     for (int j = 0; j < numberOfColumns; j++) {
  87.                         matrix[i][j] = fileScanner.nextInt();
  88.                     }
  89.                 }
  90.             } catch (Exception ex) {
  91.                 System.out.println("Некорректные данные в файле.");
  92.                 path = inputPathToFile();
  93.                 isIncorrect = true;
  94.             }
  95.             if (!isIncorrect && (numberOfColumns < 2 || numberOfColumns > 5 || numberOfLines < 2 || numberOfLines > 5))
  96.             {
  97.                 System.out.println("Некорректные данные в файле.");
  98.                 path = inputPathToFile();
  99.                 isIncorrect = true;
  100.             }
  101.         }while (isIncorrect);
  102.         return matrix;
  103.     }
  104.  
  105.     static int[][] receiveMatrixFromConsole(int numberOfLines, int numberOfColumns) {
  106.         int[][] matrix = new int[numberOfLines][numberOfColumns];
  107.         for (int i = 0; i < numberOfLines; i++)
  108.         {
  109.             for (int j = 0; j < numberOfColumns; j++)
  110.             {
  111.                 System.out.println("Введите значение элемента[" + (i + 1) + "]" + "[" + (j + 1) + "]");
  112.                 matrix[i][j] = inputNumber(-100, 100);
  113.             }
  114.         }
  115.         return matrix;
  116.     }
  117.  
  118.     static int counterOfSortedLines(int[][] matrix, int numberOfLines, int numberOfColumns) {
  119.         int counter, numberOfSortedLines;
  120.         numberOfSortedLines = 0;
  121.         for (int i = 0; i < numberOfLines; i++)
  122.         {
  123.             counter = 0;
  124.             for (int j = 1; j < numberOfColumns; j++)
  125.             {
  126.                 if (matrix[i][j - 1] < matrix[i][j])
  127.                 {
  128.                     counter++;
  129.                 }
  130.             }
  131.             if (counter == numberOfColumns - 1)
  132.             {
  133.                 numberOfSortedLines++;
  134.             }
  135.         }
  136.         return numberOfSortedLines;
  137.     }
  138.  
  139.     static void resultOutput(int numberOfSortedLines) {
  140.         System.out.println( "Количество строк, отсортированных по возрастанию: " + numberOfSortedLines);
  141.     }
  142.  
  143.     static int inputNumberOfLines() {
  144.         int numberOfLines;
  145.         System.out.println("Введите количество строк:");
  146.         numberOfLines = inputNumber(2, 5);
  147.         return numberOfLines;
  148.     }
  149.  
  150.     static int inputNumberOfColumns() {
  151.         int numberOfColumns;
  152.         System.out.println("Введите количество столбцов:");
  153.         numberOfColumns = inputNumber(2, 5);
  154.         return numberOfColumns;
  155.     }
  156.  
  157.     static int[][] receiveMatrix(int userWay) {
  158.         String path;
  159.         int numberOfLines, numberOfColumns;
  160.         int[][] matrix = new int[0][0];
  161.         switch (userWay)
  162.         {
  163.             case 1: {
  164.                 numberOfLines = inputNumberOfLines();
  165.                 numberOfColumns = inputNumberOfColumns();
  166.                 matrix = receiveMatrixFromConsole(numberOfLines, numberOfColumns);
  167.                 break;
  168.             }
  169.             case 2: {
  170.                 path = inputPathToFile();
  171.                 matrix = receiveMatrixFromFile(path);
  172.             }
  173.         }
  174.         return matrix;
  175.     }
  176.  
  177.     static boolean checkPermission(String path) {
  178.         File file = new File(path);
  179.         if (!file.canWrite()) {
  180.             System.out.println("Файл закрыт для записи");
  181.             return false;
  182.         }
  183.         return true;
  184.     }
  185.  
  186.     static boolean checkExtension(String path) {
  187.         int lastIndex;
  188.         lastIndex = path.length() - 1;
  189.         char[] pathToFile = path.toCharArray();
  190.             if (pathToFile[lastIndex] != 't' || pathToFile[lastIndex - 1] != 'x' || pathToFile[lastIndex - 2] != 't' || pathToFile[lastIndex - 3] != '.')
  191.             {
  192.                 System.out.println("Файл имеет неверное расширение. ");
  193.                 return false;
  194.             }
  195.             return true;
  196.     }
  197.  
  198.     static void checkOutputFile(String path) {
  199.         boolean isIncorrect;
  200.         do {
  201.             isIncorrect = false;
  202.             if (!checkPermission(path) || !checkExtension(path)) {
  203.                 isIncorrect = true;
  204.                 path = inputPathToFile();
  205.             }
  206.         } while (isIncorrect);
  207.     }
  208.  
  209.     static void printResultInFile(String path, int numberOfSortedLines) {
  210.         try {
  211.             FileWriter writer = new FileWriter(path);
  212.             writer.write("Количество отсортированных по возрастанию строк: " + numberOfSortedLines);
  213.             writer.flush();
  214.             writer.close();
  215.         } catch (IOException e) {
  216.             e.printStackTrace();
  217.         }
  218.     }
  219.  
  220.     static void userWayOfOutput(int numberOfSortedLines) {
  221.         String userWay;
  222.         char checkUserWay;
  223.         System.out.println("Если хотите записать результат в файл, введите '1'. Если не хотите - введите другой символ:");
  224.         userWay = consoleScanner.nextLine();
  225.         checkUserWay = userWay.charAt(0);
  226.         if (checkUserWay == '1')
  227.         {
  228.             String path = inputPathToFile();
  229.             checkOutputFile(path);
  230.             printResultInFile(path, numberOfSortedLines);
  231.             System.out.println("Результат записан в файл. \n");
  232.         }
  233.     }
  234. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement