Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.io.FileWriter;
- import java.io.FileReader;
- import java.io.BufferedWriter;
- import java.io.BufferedReader;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.util.Scanner;
- public class Main {
- static boolean chooseInOutType(String messageType) {
- Scanner scan = new Scanner(System.in);
- if (messageType.equals("in")) {
- System.out.println("В случае, если вы хотите ввести массив из файла, введите F. Если же вы хотите ввести строку из консоли, введите С");
- } else if (messageType.equals("out")) {
- System.out.println("В случае, если вы хотите произвести вывод в файл, введите F. Если же вы хотите произвести вывод только на экран, введите C");
- }
- boolean isIncorrectAnswer = true;
- do {
- char typedLetter = scan.next().charAt(0);
- typedLetter = Character.toUpperCase(typedLetter);
- if (typedLetter == 'F') {
- return true;
- } else if (typedLetter == 'C') {
- return false;
- } else {
- System.out.println("Был введён некорректный ответ. Ответом должен быть символ F или C");
- }
- } while (isIncorrectAnswer);
- return false;
- }
- static int readIntFromFile(String inputFileName) throws IOException {
- BufferedReader input = new BufferedReader(new FileReader(inputFileName));
- String text = input.readLine();
- int inputNumber = Integer.parseInt(text);
- input.close();
- return inputNumber;
- }
- static String readFileName() {
- Scanner scan = new Scanner(System.in);
- String fileName = null;
- boolean isIncorrectFile = true;
- do {
- try {
- isIncorrectFile = true;
- System.out.print("Укажите имя файла, из которого хотите считать массив: ");
- fileName = scan.nextLine();
- fileName += ".txt";
- int testNum = readIntFromFile(fileName);
- isIncorrectFile = false;
- } catch (FileNotFoundException e) {
- System.out.println("Ошибка. Указанный файл не найден.");
- } catch (IOException e) {
- System.out.println("Ошибка. Невозможно открыть указанный файл.");
- }
- } while (isIncorrectFile);
- return fileName;
- }
- static int[] readArrayFromFile(String inputFileName) throws IOException {
- BufferedReader input = new BufferedReader(new FileReader(inputFileName));
- String text = input.readLine();
- String[] rowValue;
- int matrixLength = Integer.parseInt(text);
- int[] arrayForInput = new int[matrixLength];
- text = input.readLine();
- rowValue = text.split(" ");
- for (int i = 0; i < rowValue.length; i++) {
- arrayForInput[i] = Integer.parseInt(rowValue[i]);
- }
- input.close();
- return arrayForInput;
- }
- static int inputCheckedNumber(int min, int max) {
- Scanner scan = new Scanner(System.in);
- boolean isIncorrectNumber = true;
- int number = 0;
- do{
- try{
- number = scan.nextInt();
- if ((number > min) && (number < max)){
- isIncorrectNumber = false;
- } else{
- System.out.printf("Ошибка ввода. Введите число от %d до %d \n", min, max);
- }
- } catch(Exception e) {
- System.out.printf("Ошибка ввода. Введите число от %d до %d \n", min, max);
- scan.next();
- }
- }while (isIncorrectNumber);
- return number;
- }
- static int[] readArrayFromConsole(){
- System.out.println("Укажите размер массива. Ввести необходимо натуральное число до 10");
- int matrixLength = inputCheckedNumber(0, 20);
- int[] inputArray = new int[matrixLength];
- for (int i = 0; i < inputArray.length; i++){
- System.out.printf("Введите элемент массива [%d] \n", i);
- inputArray[i] = inputCheckedNumber(-10000, 10000);
- }
- return inputArray;
- }
- static int[] createArray() throws IOException {
- boolean fileInput = chooseInOutType("in");
- int[] createdArray;
- if (fileInput){
- String inputFileName = readFileName();
- createdArray = readArrayFromFile(inputFileName);
- } else {
- createdArray = readArrayFromConsole();
- }
- return createdArray;
- }
- static int[] insertionSort(int[] brokenArray){
- int j;
- int temp;
- for (int i = 1; i < brokenArray.length; i++){
- j = i;
- temp = brokenArray[i];
- while ((j > 0) && (brokenArray[j - 1] > temp)){
- brokenArray[j] = brokenArray[j - 1];
- j--;
- }
- brokenArray[j] = temp;
- }
- return brokenArray;
- }
- static void clearFile(String fileName) throws IOException {
- FileWriter writer = new FileWriter(fileName);
- writer.close();
- }
- static String chooseOutputFile() throws IOException {
- Scanner scan = new Scanner(System.in);
- boolean isIncorrectFile = true;
- String outputFileName;
- do {
- System.out.println("Укажите название файла, в который хотите произвести запись");
- outputFileName = scan.nextLine();
- outputFileName += ".txt";
- Path outputFile = Paths.get(outputFileName);
- if (Files.exists(outputFile)) {
- clearFile(outputFileName);
- isIncorrectFile = false;
- } else {
- System.out.println("Файл с указанным названием не существует. Если вы желаете создать файл с указанным именем, введите Y, в обратном случае введите N");
- boolean isIncorrectAnswer = true;
- do {
- char answer = scan.next().charAt(0);
- answer = Character.toUpperCase(answer);
- if (answer == 'Y') {
- clearFile(outputFileName);
- isIncorrectFile = false;
- isIncorrectAnswer = false;
- } else if (answer == 'N') {
- isIncorrectAnswer = false;
- } else {
- System.out.println("Ошибка. Был введён некорректный ответ. Повторите попытку");
- }
- } while (isIncorrectAnswer);
- }
- } while (isIncorrectFile);
- return outputFileName;
- }
- static void writelnStrInFile(String fileName, String str) throws IOException {
- BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
- writer.write(str);
- writer.newLine();
- writer.close();
- }
- static void printArrayToFile(String outputFileName, int[] printedArray) throws IOException {
- BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName, true));
- for (int i = 0; i < printedArray.length; i++) {
- writer.write(printedArray[i] + " ");
- }
- }
- static void printArrayToDisplay(int[] printedArray){
- for (int i = 0; i < printedArray.length; i++) {
- System.out.printf("%d ", printedArray[i]);
- }
- System.out.println();
- }
- static void printToFile(int[] printedArray) throws IOException {
- String outputFileName = chooseOutputFile();
- writelnStrInFile(outputFileName, "Отсортированный массив: ");
- printArrayToFile(outputFileName, printedArray);
- System.out.println("Запись в файл успешно произведена");
- }
- static void printResult(int[] resultArray) throws IOException {
- System.out.println("Отсортированный массив: ");
- printArrayToDisplay(resultArray);
- boolean fileOutput = chooseInOutType("out");
- if (fileOutput) {
- printToFile(resultArray);
- }
- }
- public static void main(String[] args) throws IOException {
- System.out.println("Данная программа создаёт массив целых чисел и сортирует его, используя метод сортировки простыми вставками");
- int[] numArray = createArray();
- numArray = insertionSort(numArray);
- printResult(numArray);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement