Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package don23;
- import java.io.*;
- import java.util.Arrays;
- import java.util.Scanner;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class Main {
- public static Scanner scan = new Scanner(System.in);
- static int getArraySize()
- {
- int order = 0;
- boolean IsNotCorrect;
- do
- {
- System.out.println("Введите размер массива: ");
- IsNotCorrect = false;
- try
- {
- order = Integer.parseInt(scan.nextLine());
- }
- catch (Exception e)
- {
- IsNotCorrect = true;
- System.out.println("Размер массива должен быть положительным числом.");
- }
- if (!IsNotCorrect && (((order < 2) || (order > 10000))))
- {
- System.out.println("Размер массива должен принадлежать промежутку от 1 до 10000");
- IsNotCorrect = true;
- }
- } while (IsNotCorrect);
- return order;
- }
- static int getArrayElement(int prev)
- {
- int element = 0;
- boolean IsNotCorrect;
- do
- {
- System.out.println("Введите элемент массива: ");
- IsNotCorrect = false;
- try
- {
- element = Integer.parseInt(scan.nextLine());
- }
- catch (Exception e)
- {
- IsNotCorrect = true;
- System.out.println("Элемент массива должен быть числом.");
- }
- if (!IsNotCorrect && (((element < prev+1) || (element > 2147000000))))
- {
- System.out.println("Элемент массива должен быть больше " + prev + " и меньше 2147000000");
- IsNotCorrect = true;
- }
- } while (IsNotCorrect);
- return element;
- }
- static int[] сreateArray(int size)
- {
- int[] arr = new int[size];
- arr[0] = getArrayElement(-2147000000);//первый элемент должен быть больше минимального значения int
- for (int i = 1; i < size; i++)
- arr[i] = getArrayElement(arr[i - 1]);//сравниваем следующий элемент с предыдущим, чтобы след был больше
- return arr;
- }
- static void printArray(int[] arr)
- {
- System.out.println();
- for (int i = 0; i < arr.length; i++) {
- System.out.print(arr[i] + "\t");
- }
- System.out.println();
- }
- static int[] calculateArrayByCondition(int[] a, int[] b)
- {
- int d = 0;
- int i = 0;
- int j = 0;
- int min = 0;
- int[] c = new int[a.length + b.length];
- while ((i < a.length) && (j < b.length))
- {
- if (a[i] < b[j])
- {
- c[d++] = a[i++];
- }
- else if (a[i] > b[j])
- {
- c[d++] = b[j++];
- }
- else
- {
- c[d++] = a[i++];
- j++;
- }
- }
- while (i < a.length)
- c[d++] = a[i++];
- while (j < b.length)
- c[d++] = b[j++];
- boolean isContinue = true;
- for (i = 0; i < d; i++)
- {
- for (j = 0; j < d - i; j++)
- {
- if (j + 1 == d)
- isContinue = false;
- if ((c[j] > c[j + 1]) && (isContinue))
- {
- min = c[j];
- c[j] = c[j + 1];
- c[j + 1] = min;
- }
- }
- }
- return Arrays.copyOf(c, d);
- }
- static String getOutputDirectory()
- {
- String patho;
- boolean isIncorrect;
- isIncorrect = true;
- do
- {
- System.out.println("Введите директорию, в которую хотите сохранить результат:");
- patho = scan.nextLine();
- var file = new File(patho);
- if (file.exists())
- isIncorrect = false;
- else
- System.out.println("Такой директории не существует. Попробуйте ещё раз.");
- } while (isIncorrect);
- return patho;
- }
- static void printResultToFile(int[] a, int[] b, int[] c) throws IOException {
- var patho = getOutputDirectory();
- FileWriter myWriter = new FileWriter(patho + "output.txt");
- myWriter.write("Для массивов\n");
- for (int i = 0; i < a.length; i++)
- {
- myWriter.write(String.format("%6d", a[i]));
- }
- myWriter.write("\n");
- for (int i = 0; i < b.length; i++)
- {
- myWriter.write(String.format("%6d", b[i]));
- }
- myWriter.write("\n");
- myWriter.write("Упорядоченный массив без повторений:");
- myWriter.write("\n");
- for (int i = 0; i < c.length; i++)
- {
- myWriter.write(String.format("%6d", c[i]));
- }
- myWriter.close();
- System.out.println("Ответ сохранен по указанному пути.");
- }
- static void workWithConsole() throws IOException {
- int m, n;
- int[] a;
- int[] b;
- m = getArraySize();
- a = сreateArray(m);
- n = getArraySize();
- b = сreateArray(n);
- printArray(a);
- printArray(b);
- int[] c = calculateArrayByCondition(a, b);
- System.out.println("Новый массив:");
- printArray(c);
- printResultToFile(a, b, c);
- }
- static boolean isFileCorrect(String path) throws FileNotFoundException {
- FileReader reader = new FileReader(path);
- Scanner scanner = new Scanner(reader);
- int size;
- boolean isCorrect = true;
- try
- {
- size = scanner.nextInt();
- scanner.nextLine();
- Matcher matcher = Pattern.compile("\\d+").matcher(scanner.nextLine());
- int iCount = 0;
- while (matcher.find()) {
- iCount++;
- }
- //scanner.nextLine();
- if (iCount != size)
- isCorrect = false;
- iCount = 0;
- size = scanner.nextInt();
- scanner.nextLine();
- matcher = Pattern.compile("\\d+").matcher(scanner.nextLine());
- while (matcher.find() && isCorrect) {
- iCount++;
- }
- if (iCount != size)
- isCorrect = false;
- }
- catch (Exception e)
- {
- isCorrect = false;
- }
- return isCorrect;
- }
- static String getTaskFilePath() throws IOException {
- String path;
- boolean isIncorrect = true;
- do
- {
- System.out.println("Введите абсолютный путь к файлу: ");
- path = scan.nextLine();
- var file = new File(path);
- if (!file.exists())
- {
- System.out.println("Файл не найден. Проверьте введённый путь.");
- }
- else
- {
- if (isFileCorrect(path))
- isIncorrect = false;
- else
- System.out.println("Проверьте данные в файле. Это должны быть числа, записанные в виде матрицы. Порядок матрицы должен соответствовать введённому.");
- }
- } while (isIncorrect);
- return path;
- }
- static int[][] сreateArraysFromFile(String path) throws FileNotFoundException {
- FileReader reader = new FileReader(path);
- Scanner scanner = new Scanner(reader);
- int[] a = new int[scanner.nextInt()];
- scanner.nextLine();
- String[] strParts = scanner.nextLine().split(" ");
- for(int i = 0 ; i < a.length ; i++)
- {
- a[i] = Integer.parseInt(strParts[i]);
- }
- int[] b = new int[scanner.nextInt()];
- scanner.nextLine();
- strParts = scanner.nextLine().split(" ");
- for(int i = 0 ; i < b.length ; i++)
- {
- b[i] = Integer.parseInt(strParts[i]);
- }
- return new int[][]{a, b};
- }
- static void workWithFile() throws IOException {
- int[] a = null;
- int[] b = null;
- int[][] ab = сreateArraysFromFile(getTaskFilePath());
- a = ab[0];
- b = ab[1];
- printArray(a);
- printArray(b);
- int[] c = calculateArrayByCondition(a, b);
- System.out.println("Новый массив:");
- printArray(c);
- printResultToFile(a, b, c);
- }
- static void setProgramWorkType() throws IOException {
- int answer = 0;
- boolean isNotCorrect;
- do
- {
- System.out.println("1 - работать с консолью, 2 - с файлом: ");
- isNotCorrect = false;
- try
- {
- answer = Integer.parseInt(scan.nextLine());
- }
- catch (Exception e)
- {
- isNotCorrect = true;
- System.out.println("Введите число!");
- }
- if (!isNotCorrect && (((answer < 1) || (answer > 2))))
- {
- System.out.println("Выберите один из предложенных вариантов!");
- isNotCorrect = true;
- }
- } while (isNotCorrect);
- if (answer == 1)
- workWithConsole();
- else
- workWithFile();
- }
- public static void main(String[] args) throws IOException {
- setProgramWorkType();
- }
- }
Advertisement
Advertisement