Advertisement
believe_me

Untitled

Oct 28th, 2021
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.41 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 receiveNumberOfLinesFromFile(String path, Scanner fileScanner) {
  73.         boolean isIncorrect;
  74.         int numberOfLines;
  75.         do {
  76.             isIncorrect = false;
  77.             numberOfLines = fileScanner.nextInt();
  78.             if (numberOfLines < 1)
  79.             {
  80.                 isIncorrect = true;
  81.                 System.out.println("Некорректные данные в файле.");
  82.                 path = inputPathToFile();
  83.             }
  84.         } while (isIncorrect);
  85.         return numberOfLines;
  86.     }
  87.  
  88.     static int receiveNumberOfColumnsFromFile(String path, Scanner fileScanner) {
  89.         boolean isIncorrect;
  90.         int numberOfColumns;
  91.         do {
  92.             isIncorrect = false;
  93.             numberOfColumns = fileScanner.nextInt();
  94.             if (numberOfColumns < 1)
  95.             {
  96.                 isIncorrect = true;
  97.                 System.out.println("Некорректные данные в файле.");
  98.                 path = inputPathToFile();
  99.             }
  100.         } while (isIncorrect);
  101.         return numberOfColumns;
  102.     }
  103.  
  104.     static int[][] receiveMatrixFromFile(String path) {
  105.         File file = new File(path);
  106.         int[][] matrix = null;
  107.         try {
  108.             Scanner fileScanner = new Scanner(file);
  109.             int numberOfLines = receiveNumberOfLinesFromFile(path, fileScanner);
  110.             int numberOfColumns = receiveNumberOfColumnsFromFile(path, fileScanner);
  111.             matrix = new int[numberOfLines][numberOfColumns];
  112.             for (int i = 0; i < numberOfLines; i++) {
  113.                 for (int j = 0; j < numberOfColumns; j++) {
  114.                     matrix[i][j] = fileScanner.nextInt();
  115.                 }
  116.             }
  117.         }catch (FileNotFoundException e) {
  118.             e.printStackTrace();
  119.         }
  120.         return matrix;
  121.     }
  122.  
  123.     static int[][] receiveMatrixFromConsole(int numberOfLines, int numberOfColumns) {
  124.         int[][] matrix = new int[numberOfLines][numberOfColumns];
  125.         for (int i = 0; i < numberOfLines; i++)
  126.         {
  127.             for (int j = 0; j < numberOfColumns; j++)
  128.             {
  129.                 System.out.println("Введите значение элемента[" + (i + 1) + "]" + "[" + (j + 1) + "]");
  130.                 matrix[i][j] = inputNumber(-100, 100);
  131.             }
  132.         }
  133.         return matrix;
  134.     }
  135.  
  136.     static int counterOfSortedLines(int[][] matrix, int numberOfLines, int numberOfColumns) {
  137.         int counter, numberOfSortedLines;
  138.         numberOfSortedLines = 0;
  139.         for (int i = 0; i < numberOfLines; i++)
  140.         {
  141.             counter = 0;
  142.             for (int j = 1; j < numberOfColumns; j++)
  143.             {
  144.                 if (matrix[i][j - 1] < matrix[i][j])
  145.                 {
  146.                     counter++;
  147.                 }
  148.             }
  149.             if (counter == numberOfColumns - 1)
  150.             {
  151.                 numberOfSortedLines++;
  152.             }
  153.         }
  154.         return numberOfSortedLines;
  155.     }
  156.  
  157.     static void resultOutput(int numberOfSortedLines) {
  158.         System.out.println( "Количество строк, отсортированных по возрастанию: " + numberOfSortedLines);
  159.     }
  160.  
  161.     static int inputNumberOfLines() {
  162.         int numberOfLines;
  163.         System.out.println("Введите количество строк:");
  164.         numberOfLines = inputNumber(2, 5);
  165.         return numberOfLines;
  166.     }
  167.  
  168.     static int inputNumberOfColumns() {
  169.         int numberOfColumns;
  170.         System.out.println("Введите количество столбцов:");
  171.         numberOfColumns = inputNumber(2, 5);
  172.         return numberOfColumns;
  173.     }
  174.  
  175.     static int[][] receiveMatrix(int userWay) {
  176.         String path;
  177.         int numberOfLines, numberOfColumns;
  178.         int[][] matrix = new int[0][0];
  179.         switch (userWay)
  180.         {
  181.             case 1: {
  182.                 numberOfLines = inputNumberOfLines();
  183.                 numberOfColumns = inputNumberOfColumns();
  184.                 matrix = receiveMatrixFromConsole(numberOfLines, numberOfColumns);
  185.                 break;
  186.             }
  187.             case 2: {
  188.                 path = inputPathToFile();
  189.                 matrix = receiveMatrixFromFile(path);
  190.                 break;
  191.             }
  192.         }
  193.         return matrix;
  194.     }
  195.  
  196.     static boolean checkPermission(String path) {
  197.         File file = new File(path);
  198.         if (!file.canWrite()) {
  199.             System.out.println("Файл закрыт для записи");
  200.             return false;
  201.         }
  202.         return true;
  203.     }
  204.  
  205.     static boolean checkExtension(String path) {
  206.         int lastIndex;
  207.         lastIndex = path.length() - 1;
  208.         char[] pathToFile = path.toCharArray();
  209.             if (pathToFile[lastIndex] != 't' || pathToFile[lastIndex - 1] != 'x' || pathToFile[lastIndex - 2] != 't' || pathToFile[lastIndex - 3] != '.')
  210.             {
  211.                 System.out.println("Файл имеет неверное расширение. ");
  212.                 return false;
  213.             }
  214.             return true;
  215.     }
  216.  
  217.     static void checkOutputFile(String path) {
  218.         boolean isIncorrect;
  219.         do {
  220.             isIncorrect = false;
  221.             if (!checkPermission(path) || !checkExtension(path)) {
  222.                 isIncorrect = true;
  223.                 path = inputPathToFile();
  224.             }
  225.         } while (isIncorrect);
  226.     }
  227.  
  228.     static void printResultInFile(String path, int numberOfSortedLines) {
  229.         try {
  230.             FileWriter writer = new FileWriter(path);
  231.             writer.write("Количество отсортированных по возрастанию строк: " + numberOfSortedLines);
  232.             writer.flush();
  233.             writer.close();
  234.         } catch (IOException e) {
  235.             e.printStackTrace();
  236.         }
  237.     }
  238.  
  239.     static void userWayOfOutput(int numberOfSortedLines) {
  240.         String userWay;
  241.         char checkUserWay;
  242.         System.out.println("Если хотите записать результат в файл, введите '1'. Если не хотите - введите другой символ:");
  243.         userWay = consoleScanner.nextLine();
  244.         checkUserWay = userWay.charAt(0);
  245.         if (checkUserWay == '1')
  246.         {
  247.             String path = inputPathToFile();
  248.             checkOutputFile(path);
  249.             printResultInFile(path, numberOfSortedLines);
  250.             System.out.println("Результат записан в файл. \n");
  251.         }
  252.     }
  253. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement