Advertisement
MaksNew

2_4_java

Dec 18th, 2022
972
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.07 KB | None | 0 0
  1. package don23;
  2.  
  3. import java.io.*;
  4. import java.util.Arrays;
  5. import java.util.Scanner;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8.  
  9. public class Main {
  10.  
  11.     public static Scanner scan = new Scanner(System.in);
  12.  
  13.     static int getArraySize()
  14.     {
  15.         int order = 0;
  16.         boolean IsNotCorrect;
  17.         do
  18.         {
  19.             System.out.println("Введите размер массива: ");
  20.             IsNotCorrect = false;
  21.             try
  22.             {
  23.                 order = Integer.parseInt(scan.nextLine());
  24.             }
  25.             catch (Exception e)
  26.             {
  27.                 IsNotCorrect = true;
  28.                 System.out.println("Размер массива должен быть положительным числом.");
  29.             }
  30.             if (!IsNotCorrect && (((order < 2) || (order > 10000))))
  31.             {
  32.                 System.out.println("Размер массива должен принадлежать промежутку от 1 до 10000");
  33.                 IsNotCorrect = true;
  34.             }
  35.         } while (IsNotCorrect);
  36.         return order;
  37.     }
  38.  
  39.     static int getArrayElement(int prev)
  40.     {
  41.         int element = 0;
  42.         boolean IsNotCorrect;
  43.         do
  44.         {
  45.             System.out.println("Введите элемент массива: ");
  46.             IsNotCorrect = false;
  47.             try
  48.             {
  49.                 element = Integer.parseInt(scan.nextLine());
  50.             }
  51.             catch (Exception e)
  52.             {
  53.                 IsNotCorrect = true;
  54.                 System.out.println("Элемент массива должен быть числом.");
  55.             }
  56.             if (!IsNotCorrect && (((element < prev+1) || (element > 2147000000))))
  57.             {
  58.                 System.out.println("Элемент массива должен быть больше " + prev + " и меньше 2147000000");
  59.                 IsNotCorrect = true;
  60.             }
  61.         } while (IsNotCorrect);
  62.         return element;
  63.     }
  64.  
  65.     static int[] сreateArray(int size)
  66.     {
  67.         int[] arr = new int[size];
  68.         arr[0] = getArrayElement(-2147000000);//первый элемент должен быть больше минимального значения int
  69.         for (int i = 1; i < size; i++)
  70.             arr[i] = getArrayElement(arr[i - 1]);//сравниваем следующий элемент с предыдущим, чтобы след был больше
  71.         return arr;
  72.     }
  73.  
  74.     static void printArray(int[] arr)
  75.     {
  76.         System.out.println();
  77.         for (int i = 0; i < arr.length; i++) {
  78.             System.out.print(arr[i] + "\t");
  79.         }
  80.         System.out.println();
  81.     }
  82.  
  83.     static int[] calculateArrayByCondition(int[] a, int[] b)
  84.     {
  85.         int d = 0;
  86.         int i = 0;
  87.         int j = 0;
  88.         int min = 0;
  89.         int[] c = new int[a.length + b.length];
  90.  
  91.         while ((i < a.length) && (j < b.length))
  92.         {
  93.             if (a[i] < b[j])
  94.             {
  95.                 c[d++] = a[i++];
  96.             }
  97.             else if (a[i] > b[j])
  98.             {
  99.                 c[d++] = b[j++];
  100.             }
  101.             else
  102.             {
  103.                 c[d++] = a[i++];
  104.                 j++;
  105.             }
  106.         }
  107.         while (i < a.length)
  108.             c[d++] = a[i++];
  109.         while (j < b.length)
  110.             c[d++] = b[j++];
  111.  
  112.         boolean isContinue = true;
  113.         for (i = 0; i < d; i++)
  114.         {
  115.             for (j = 0; j < d - i; j++)
  116.             {
  117.                 if (j + 1 == d)
  118.                     isContinue = false;
  119.                 if ((c[j] > c[j + 1]) && (isContinue))
  120.                 {
  121.                     min = c[j];
  122.                     c[j] = c[j + 1];
  123.                     c[j + 1] = min;
  124.                 }
  125.             }
  126.         }
  127.         return Arrays.copyOf(c, d);
  128.     }
  129.  
  130.     static String getOutputDirectory()
  131.     {
  132.         String patho;
  133.         boolean isIncorrect;
  134.         isIncorrect = true;
  135.         do
  136.         {
  137.             System.out.println("Введите директорию, в которую хотите сохранить результат:");
  138.             patho = scan.nextLine();
  139.             var file = new File(patho);
  140.             if (file.exists())
  141.                 isIncorrect = false;
  142.             else
  143.                 System.out.println("Такой директории не существует. Попробуйте ещё раз.");
  144.         } while (isIncorrect);
  145.         return patho;
  146.     }
  147.  
  148.     static void printResultToFile(int[] a, int[] b, int[] c) throws IOException {
  149.         var patho = getOutputDirectory();
  150.         FileWriter myWriter = new FileWriter(patho + "output.txt");
  151.         myWriter.write("Для массивов\n");
  152.         for (int i = 0; i < a.length; i++)
  153.         {
  154.             myWriter.write(String.format("%6d", a[i]));
  155.         }
  156.         myWriter.write("\n");
  157.         for (int i = 0; i < b.length; i++)
  158.         {
  159.             myWriter.write(String.format("%6d", b[i]));
  160.         }
  161.         myWriter.write("\n");
  162.         myWriter.write("Упорядоченный массив без повторений:");
  163.         myWriter.write("\n");
  164.         for (int i = 0; i < c.length; i++)
  165.         {
  166.             myWriter.write(String.format("%6d", c[i]));
  167.         }
  168.         myWriter.close();
  169.         System.out.println("Ответ сохранен по указанному пути.");
  170.     }
  171.  
  172.     static void workWithConsole() throws IOException {
  173.         int m, n;
  174.         int[] a;
  175.         int[] b;
  176.         m = getArraySize();
  177.         a = сreateArray(m);
  178.         n = getArraySize();
  179.         b = сreateArray(n);
  180.         printArray(a);
  181.         printArray(b);
  182.         int[] c = calculateArrayByCondition(a, b);
  183.         System.out.println("Новый массив:");
  184.         printArray(c);
  185.         printResultToFile(a, b, c);
  186.     }
  187.  
  188.     static boolean isFileCorrect(String path) throws FileNotFoundException {
  189.         FileReader reader = new FileReader(path);
  190.         Scanner scanner = new Scanner(reader);
  191.         int size;
  192.         boolean isCorrect = true;
  193.         try
  194.         {
  195.             size = scanner.nextInt();
  196.             scanner.nextLine();
  197.             Matcher matcher = Pattern.compile("\\d+").matcher(scanner.nextLine());
  198.             int iCount = 0;
  199.             while (matcher.find()) {
  200.                 iCount++;
  201.             }
  202.             //scanner.nextLine();
  203.             if (iCount != size)
  204.                 isCorrect = false;
  205.  
  206.             iCount = 0;
  207.             size = scanner.nextInt();
  208.             scanner.nextLine();
  209.             matcher = Pattern.compile("\\d+").matcher(scanner.nextLine());
  210.             while (matcher.find() && isCorrect) {
  211.                 iCount++;
  212.             }
  213.             if (iCount != size)
  214.                 isCorrect = false;
  215.         }
  216.         catch (Exception e)
  217.         {
  218.             isCorrect = false;
  219.         }
  220.         return isCorrect;
  221.     }
  222.  
  223.     static String getTaskFilePath() throws IOException {
  224.         String path;
  225.         boolean isIncorrect = true;
  226.         do
  227.         {
  228.             System.out.println("Введите абсолютный путь к файлу: ");
  229.             path = scan.nextLine();
  230.             var file = new File(path);
  231.             if (!file.exists())
  232.             {
  233.                 System.out.println("Файл не найден. Проверьте введённый путь.");
  234.             }
  235.             else
  236.             {
  237.                 if (isFileCorrect(path))
  238.                     isIncorrect = false;
  239.                 else
  240.                     System.out.println("Проверьте данные в файле. Это должны быть числа, записанные в виде матрицы. Порядок матрицы должен соответствовать введённому.");
  241.             }
  242.         } while (isIncorrect);
  243.         return path;
  244.     }
  245.  
  246.     static int[][] сreateArraysFromFile(String path) throws FileNotFoundException {
  247.         FileReader reader = new FileReader(path);
  248.         Scanner scanner = new Scanner(reader);
  249.         int[] a = new int[scanner.nextInt()];
  250.         scanner.nextLine();
  251.         String[] strParts = scanner.nextLine().split(" ");
  252.         for(int i = 0 ; i < a.length ; i++)
  253.         {
  254.             a[i] = Integer.parseInt(strParts[i]);
  255.         }
  256.         int[] b = new int[scanner.nextInt()];
  257.         scanner.nextLine();
  258.         strParts = scanner.nextLine().split(" ");
  259.         for(int i = 0 ; i < b.length ; i++)
  260.         {
  261.             b[i] = Integer.parseInt(strParts[i]);
  262.         }
  263.         return new int[][]{a, b};
  264.     }
  265.  
  266.     static void workWithFile() throws IOException {
  267.         int[] a = null;
  268.         int[] b = null;
  269.         int[][] ab = сreateArraysFromFile(getTaskFilePath());
  270.         a = ab[0];
  271.         b = ab[1];
  272.         printArray(a);
  273.         printArray(b);
  274.         int[] c = calculateArrayByCondition(a, b);
  275.         System.out.println("Новый массив:");
  276.         printArray(c);
  277.         printResultToFile(a, b, c);
  278.     }
  279.  
  280.     static void setProgramWorkType() throws IOException {
  281.         int answer = 0;
  282.         boolean isNotCorrect;
  283.         do
  284.         {
  285.             System.out.println("1 - работать с консолью, 2 - с файлом: ");
  286.             isNotCorrect = false;
  287.             try
  288.             {
  289.                 answer = Integer.parseInt(scan.nextLine());
  290.             }
  291.             catch (Exception e)
  292.             {
  293.                 isNotCorrect = true;
  294.                 System.out.println("Введите число!");
  295.             }
  296.             if (!isNotCorrect && (((answer < 1) || (answer > 2))))
  297.             {
  298.                 System.out.println("Выберите один из предложенных вариантов!");
  299.                 isNotCorrect = true;
  300.             }
  301.         } while (isNotCorrect);
  302.         if (answer == 1)
  303.             workWithConsole();
  304.         else
  305.             workWithFile();
  306.     }
  307.  
  308.     public static void main(String[] args) throws IOException {
  309.         setProgramWorkType();
  310.     }
  311. }
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement