Advertisement
Guest User

Untitled

a guest
Apr 9th, 2020
295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.05 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.io.FileWriter;
  4. import java.io.FileReader;
  5. import java.io.BufferedWriter;
  6. import java.io.BufferedReader;
  7. import java.io.FileNotFoundException;
  8. import java.io.IOException;
  9. import java.nio.file.Files;
  10. import java.nio.file.Path;
  11. import java.nio.file.Paths;
  12. import java.util.Scanner;
  13.  
  14. public class Main {
  15.  
  16.     static boolean chooseInOutType(String messageType) {
  17.         Scanner scan = new Scanner(System.in);
  18.         if (messageType.equals("in")) {
  19.             System.out.println("В случае, если вы хотите ввести массив из файла, введите F. Если же вы хотите ввести строку из консоли, введите С");
  20.         } else if (messageType.equals("out")) {
  21.             System.out.println("В случае, если вы хотите произвести вывод в файл, введите F. Если же вы хотите произвести вывод только на экран, введите C");
  22.         }
  23.         boolean isIncorrectAnswer = true;
  24.         do {
  25.             char typedLetter = scan.next().charAt(0);
  26.             typedLetter = Character.toUpperCase(typedLetter);
  27.             if (typedLetter == 'F') {
  28.                 return true;
  29.             } else if (typedLetter == 'C') {
  30.                 return false;
  31.             } else {
  32.                 System.out.println("Был введён некорректный ответ. Ответом должен быть символ F или C");
  33.             }
  34.         } while (isIncorrectAnswer);
  35.         return false;
  36.     }
  37.  
  38.     static int readIntFromFile(String inputFileName) throws IOException {
  39.         BufferedReader input = new BufferedReader(new FileReader(inputFileName));
  40.         String text = input.readLine();
  41.         int inputNumber = Integer.parseInt(text);
  42.         input.close();
  43.         return inputNumber;
  44.     }
  45.  
  46.     static String readFileName() {
  47.         Scanner scan = new Scanner(System.in);
  48.         String fileName = null;
  49.         boolean isIncorrectFile = true;
  50.         do {
  51.             try {
  52.                 isIncorrectFile = true;
  53.                 System.out.print("Укажите имя файла, из которого хотите считать массив: ");
  54.                 fileName = scan.nextLine();
  55.                 fileName += ".txt";
  56.                 int testNum = readIntFromFile(fileName);
  57.                 isIncorrectFile = false;
  58.             } catch (FileNotFoundException e) {
  59.                 System.out.println("Ошибка. Указанный файл не найден.");
  60.             } catch (IOException e) {
  61.                 System.out.println("Ошибка. Невозможно открыть указанный файл.");
  62.             }
  63.         } while (isIncorrectFile);
  64.         return fileName;
  65.     }
  66.  
  67.     static int[] readArrayFromFile(String inputFileName) throws IOException {
  68.         BufferedReader input = new BufferedReader(new FileReader(inputFileName));
  69.         String text = input.readLine();
  70.         String[] rowValue;
  71.         int matrixLength = Integer.parseInt(text);
  72.         int[] arrayForInput = new int[matrixLength];
  73.         text = input.readLine();
  74.         rowValue = text.split(" ");
  75.         for (int i = 0; i < rowValue.length; i++) {
  76.             arrayForInput[i] = Integer.parseInt(rowValue[i]);
  77.         }
  78.         input.close();
  79.         return arrayForInput;
  80.     }
  81.  
  82.     static int inputCheckedNumber(int min, int max) {
  83.         Scanner scan = new Scanner(System.in);
  84.         boolean isIncorrectNumber = true;
  85.         int number = 0;
  86.         do{
  87.             try{
  88.                 number = scan.nextInt();
  89.                 if ((number > min) && (number < max)){
  90.                     isIncorrectNumber = false;
  91.                 } else{
  92.                     System.out.printf("Ошибка ввода. Введите число от %d до %d \n", min, max);
  93.                 }
  94.             } catch(Exception e) {
  95.                 System.out.printf("Ошибка ввода. Введите число от %d до %d  \n", min, max);
  96.                 scan.next();
  97.             }
  98.         }while (isIncorrectNumber);
  99.         return number;
  100.     }
  101.  
  102.     static int[] readArrayFromConsole(){
  103.         System.out.println("Укажите размер массива. Ввести необходимо натуральное число до 10");
  104.         int matrixLength = inputCheckedNumber(0, 20);
  105.         int[] inputArray = new int[matrixLength];
  106.         for (int i = 0; i < inputArray.length; i++){
  107.             System.out.printf("Введите элемент массива [%d] \n", i);
  108.             inputArray[i] = inputCheckedNumber(-10000, 10000);
  109.         }
  110.         return inputArray;
  111.     }
  112.  
  113.     static int[] createArray() throws IOException {
  114.         boolean fileInput = chooseInOutType("in");
  115.         int[] createdArray;
  116.         if (fileInput){
  117.             String inputFileName = readFileName();
  118.             createdArray = readArrayFromFile(inputFileName);
  119.         } else {
  120.             createdArray = readArrayFromConsole();
  121.         }
  122.         return createdArray;
  123.     }
  124.  
  125.     static int[] insertionSort(int[] brokenArray){
  126.         int j;
  127.         int temp;
  128.         for (int i = 1; i < brokenArray.length; i++){
  129.             j = i;
  130.             temp = brokenArray[i];
  131.             while ((j > 0) && (brokenArray[j - 1] > temp)){
  132.                 brokenArray[j] = brokenArray[j - 1];
  133.                 j--;
  134.             }
  135.             brokenArray[j] = temp;
  136.         }
  137.         return brokenArray;
  138.     }
  139.  
  140.     static void clearFile(String fileName) throws IOException {
  141.         FileWriter writer = new FileWriter(fileName);
  142.         writer.close();
  143.     }
  144.  
  145.     static String chooseOutputFile() throws IOException {
  146.         Scanner scan = new Scanner(System.in);
  147.         boolean isIncorrectFile = true;
  148.         String outputFileName;
  149.         do {
  150.             System.out.println("Укажите название файла, в который хотите произвести запись");
  151.             outputFileName = scan.nextLine();
  152.             outputFileName += ".txt";
  153.             Path outputFile = Paths.get(outputFileName);
  154.             if (Files.exists(outputFile)) {
  155.                 clearFile(outputFileName);
  156.                 isIncorrectFile = false;
  157.             } else {
  158.                 System.out.println("Файл с указанным названием не существует. Если вы желаете создать файл с указанным именем, введите Y, в обратном случае введите N");
  159.                 boolean isIncorrectAnswer = true;
  160.                 do {
  161.                     char answer = scan.next().charAt(0);
  162.                     answer = Character.toUpperCase(answer);
  163.                     if (answer == 'Y') {
  164.                         clearFile(outputFileName);
  165.                         isIncorrectFile = false;
  166.                         isIncorrectAnswer = false;
  167.                     } else if (answer == 'N') {
  168.                         isIncorrectAnswer = false;
  169.                     } else {
  170.                         System.out.println("Ошибка. Был введён некорректный ответ. Повторите попытку");
  171.                     }
  172.                 } while (isIncorrectAnswer);
  173.             }
  174.         } while (isIncorrectFile);
  175.         return outputFileName;
  176.     }
  177.  
  178.     static void writelnStrInFile(String fileName, String str) throws IOException {
  179.         BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
  180.         writer.write(str);
  181.         writer.newLine();
  182.         writer.close();
  183.     }
  184.  
  185.     static void printArrayToFile(String outputFileName, int[] printedArray) throws IOException {
  186.         BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName, true));
  187.         for (int i = 0; i < printedArray.length; i++) {
  188.             writer.write(printedArray[i] + " ");
  189.         }
  190.     }
  191.  
  192.     static void printArrayToDisplay(int[] printedArray){
  193.         for (int i = 0; i < printedArray.length; i++) {
  194.             System.out.printf("%d ", printedArray[i]);
  195.         }
  196.         System.out.println();
  197.     }
  198.  
  199.     static void printToFile(int[] printedArray) throws IOException {
  200.         String outputFileName = chooseOutputFile();
  201.         writelnStrInFile(outputFileName, "Отсортированный массив: ");
  202.         printArrayToFile(outputFileName, printedArray);
  203.         System.out.println("Запись в файл успешно произведена");
  204.     }
  205.  
  206.     static void printResult(int[] resultArray) throws IOException {
  207.         System.out.println("Отсортированный массив: ");
  208.         printArrayToDisplay(resultArray);
  209.         boolean fileOutput = chooseInOutType("out");
  210.         if (fileOutput) {
  211.             printToFile(resultArray);
  212.         }
  213.     }
  214.  
  215.     public static void main(String[] args) throws IOException {
  216.         System.out.println("Данная программа создаёт массив целых чисел и  сортирует его, используя метод сортировки простыми вставками");
  217.         int[] numArray = createArray();
  218.         numArray = insertionSort(numArray);
  219.         printResult(numArray);
  220.     }
  221. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement