Advertisement
Guest User

Untitled

a guest
Apr 8th, 2020
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.35 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.HashSet;
  13. import java.util.Scanner;
  14.  
  15. public class Main {
  16.  
  17.    static boolean chooseInOutType(String messageType) {
  18.       Scanner scan = new Scanner(System.in);
  19.       if (messageType.equals("in")) {
  20.          System.out.println("В случае, если вы хотите ввести строку из файла, введите F. Если же вы хотите ввести строку из консоли, введите С");
  21.       } else if (messageType.equals("out")) {
  22.          System.out.println("В случае, если вы хотите произвести вывод в файл, введите F. Если же вы хотите произвести вывод только на экран, введите C");
  23.       }
  24.       boolean isIncorrectAnswer = true;
  25.       do {
  26.          char typedLetter = scan.next().charAt(0);
  27.          typedLetter = Character.toUpperCase(typedLetter);
  28.          if (typedLetter == 'F') {
  29.             return true;
  30.          } else if (typedLetter == 'C') {
  31.             return false;
  32.          } else {
  33.             System.out.println("Ошибка. Был введён некорректный ответ. Повторите попытку.");
  34.          }
  35.       } while (isIncorrectAnswer);
  36.       return false;
  37.    }
  38.  
  39.    static String readStringFromFile(String inputFileName) throws IOException {
  40.       BufferedReader input = new BufferedReader(new FileReader(inputFileName));
  41.       String inputString = input.readLine();
  42.       input.close();
  43.       return inputString;
  44.    }
  45.  
  46.    static String readNumberString() {
  47.       HashSet<String> digits = new HashSet<>(10);
  48.       for (int i = 0; i < 10; i++) {
  49.          digits.add(Integer.toString(i));
  50.       }
  51.       Scanner scan = new Scanner(System.in);
  52.       boolean isIncorrectString;
  53.       String numberString= "";
  54.       System.out.println("Введите четыре натуральных числа до 2000");
  55.       do {
  56.          isIncorrectString = false;
  57.          numberString = scan.nextLine();
  58.          int i = 0;
  59.          while ((i < numberString.length()) && (!isIncorrectString)) {
  60.             if (numberString.charAt(i) == ' ') {
  61.                i++;
  62.             } else {
  63.                if (digits.contains((Character.toString(numberString.charAt(i))))) {
  64.                   i++;
  65.                } else {
  66.                   isIncorrectString = true;
  67.                   System.out.println("Ошибка. Введите четыре натуральных числа до 2000");
  68.                }
  69.             }
  70.          }
  71.       } while (isIncorrectString);
  72.       return numberString;
  73.    }
  74.  
  75.    static String deleteExcessSpaces(String brokenStr) {
  76.       while (brokenStr.contains("  ")) {
  77.          brokenStr = brokenStr.replaceAll(" {2}", " ");
  78.       }
  79.       return brokenStr;
  80.    }
  81.  
  82.    static int[] breakStringIntoArray(String inputStr) {
  83.       String[] strDecNumbers = inputStr.split(" ");
  84.       int[] decNumbers = new int[strDecNumbers.length];
  85.       for (int i = 0; i < decNumbers.length; i++) {
  86.          decNumbers[i] = Integer.parseInt(strDecNumbers[i]);
  87.       }
  88.       return decNumbers;
  89.    }
  90.  
  91.    static String decToRoman(int decNumber) {
  92.       int[] decDigits = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
  93.       String[] romanDigits = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};
  94.       int i = 12;
  95.       String strResult = " ";
  96.       while (decNumber > 0) {
  97.          if (decDigits[i] > decNumber) {
  98.             i--;
  99.          } else {
  100.             decNumber -= decDigits[i];
  101.             strResult += romanDigits[i];
  102.          }
  103.       }
  104.       return strResult;
  105.    }
  106.  
  107.    static String convertString(String decStr){
  108.       int[] decNumbers = breakStringIntoArray(decStr);
  109.       String romStr = "";
  110.       for (int i = 0; i < decNumbers.length; i++) {
  111.          romStr += decToRoman(decNumbers[i]);
  112.       }
  113.       return romStr;
  114.    }
  115.  
  116.    static String readFileName() {
  117.       Scanner scan = new Scanner(System.in);
  118.       String fileName = null;
  119.       boolean isIncorrectFile = true;
  120.       do {
  121.          try {
  122.             System.out.print("Укажите имя файла, из которого хотите считать строку: ");
  123.             fileName = scan.nextLine();
  124.             fileName += ".txt";
  125.             isIncorrectFile = false;
  126.             String testString = readStringFromFile(fileName);
  127.          } catch (FileNotFoundException e) {
  128.             System.out.println("Ошибка. Указанный файл не найден.");
  129.          } catch (IOException e) {
  130.             System.out.println("Ошибка. чвми");
  131.          }
  132.       } while (isIncorrectFile);
  133.       return fileName;
  134.    }
  135.  
  136.    static void clearFile(String fileName) throws IOException {
  137.       FileWriter writer = new FileWriter(fileName);
  138.       writer.close();
  139.    }
  140.  
  141.    static String chooseOutputFile() throws IOException {
  142.       Scanner scan = new Scanner(System.in);
  143.       boolean isIncorrectFile = true;
  144.       String outputFileName;
  145.       do {
  146.          System.out.println("Укажите название файла, в который хотите произвести запись");
  147.          outputFileName = scan.nextLine();
  148.          outputFileName += ".txt";
  149.          Path outputFile = Paths.get(outputFileName);
  150.          if (Files.exists(outputFile)) {
  151.             clearFile(outputFileName);
  152.             isIncorrectFile = false;
  153.          } else {
  154.             System.out.println("Файл с указанным названием не существует. Если вы желаете создать файл с указанным именем, введите Y, в обратном случае введите N");
  155.             boolean isIncorrectAnswer = true;
  156.             do {
  157.                char answer = scan.next().charAt(0);
  158.                answer = Character.toUpperCase(answer);
  159.                if (answer == 'Y') {
  160.                   clearFile(outputFileName);
  161.                   isIncorrectFile = false;
  162.                   isIncorrectAnswer = false;
  163.                } else if (answer == 'N') {
  164.                   isIncorrectAnswer = false;
  165.                } else {
  166.                   System.out.println("Ошибка. Был введён некорректный ответ. Повторите попытку");
  167.                }
  168.             } while (isIncorrectAnswer);
  169.          }
  170.       } while (isIncorrectFile);
  171.       return outputFileName;
  172.    }
  173.  
  174.    static void writelnStrInFile(String fileName, String str) throws IOException {
  175.       BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
  176.       writer.write(str);
  177.       writer.newLine();
  178.       writer.close();
  179.    }
  180.  
  181.    static String readString() throws IOException {
  182.       String inStr;
  183.       boolean fileInput = chooseInOutType("in");
  184.       if (fileInput) {
  185.          String inputFileName = readFileName();
  186.          inStr = readStringFromFile(inputFileName);
  187.       } else {
  188.          inStr = readNumberString();
  189.       }
  190.       return inStr;
  191.    }
  192.  
  193.    static void printToFile(String printStr) throws IOException {
  194.       String outputFileName = chooseOutputFile();
  195.       writelnStrInFile(outputFileName, "Числа, представленные римскими цифрами: ");
  196.       writelnStrInFile(outputFileName, printStr);
  197.       System.out.println("Запись в файл успешно произведена");
  198.    }
  199.  
  200.    static void printResult(String decStr, String romStr) throws IOException {
  201.       System.out.println("Числа, представленные арабскими цифрами: " + decStr);
  202.       System.out.println("Числа, представленные рисмкими цифрами: " + romStr);
  203.       boolean fileOutput = chooseInOutType("out");
  204.       if (fileOutput) {
  205.          printToFile(romStr);
  206.       }
  207.    }
  208.  
  209.    public static void main(String[] args) throws IOException {
  210.       System.out.println("Данная программа переводит до 4 введённых чисел, представленных арабскими цифрами, в римскую систему счисления");
  211.       String fullDecStr = readString();
  212.       fullDecStr = deleteExcessSpaces(fullDecStr);
  213.       String fullRomanStr = convertString(fullDecStr);
  214.       printResult(fullDecStr, fullRomanStr);
  215.    }
  216. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement