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.HashSet;
- 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("Ошибка. Был введён некорректный ответ. Повторите попытку.");
- }
- } while (isIncorrectAnswer);
- return false;
- }
- static String readStringFromFile(String inputFileName) throws IOException {
- BufferedReader input = new BufferedReader(new FileReader(inputFileName));
- String inputString = input.readLine();
- input.close();
- return inputString;
- }
- static String readNumberString() {
- HashSet<String> digits = new HashSet<>(10);
- for (int i = 0; i < 10; i++) {
- digits.add(Integer.toString(i));
- }
- Scanner scan = new Scanner(System.in);
- boolean isIncorrectString;
- String numberString= "";
- System.out.println("Введите четыре натуральных числа до 2000");
- do {
- isIncorrectString = false;
- numberString = scan.nextLine();
- int i = 0;
- while ((i < numberString.length()) && (!isIncorrectString)) {
- if (numberString.charAt(i) == ' ') {
- i++;
- } else {
- if (digits.contains((Character.toString(numberString.charAt(i))))) {
- i++;
- } else {
- isIncorrectString = true;
- System.out.println("Ошибка. Введите четыре натуральных числа до 2000");
- }
- }
- }
- } while (isIncorrectString);
- return numberString;
- }
- static String deleteExcessSpaces(String brokenStr) {
- while (brokenStr.contains(" ")) {
- brokenStr = brokenStr.replaceAll(" {2}", " ");
- }
- return brokenStr;
- }
- static int[] breakStringIntoArray(String inputStr) {
- String[] strDecNumbers = inputStr.split(" ");
- int[] decNumbers = new int[strDecNumbers.length];
- for (int i = 0; i < decNumbers.length; i++) {
- decNumbers[i] = Integer.parseInt(strDecNumbers[i]);
- }
- return decNumbers;
- }
- static String decToRoman(int decNumber) {
- int[] decDigits = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
- String[] romanDigits = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};
- int i = 12;
- String strResult = " ";
- while (decNumber > 0) {
- if (decDigits[i] > decNumber) {
- i--;
- } else {
- decNumber -= decDigits[i];
- strResult += romanDigits[i];
- }
- }
- return strResult;
- }
- static String convertString(String decStr){
- int[] decNumbers = breakStringIntoArray(decStr);
- String romStr = "";
- for (int i = 0; i < decNumbers.length; i++) {
- romStr += decToRoman(decNumbers[i]);
- }
- return romStr;
- }
- static String readFileName() {
- Scanner scan = new Scanner(System.in);
- String fileName = null;
- boolean isIncorrectFile = true;
- do {
- try {
- System.out.print("Укажите имя файла, из которого хотите считать строку: ");
- fileName = scan.nextLine();
- fileName += ".txt";
- isIncorrectFile = false;
- String testString = readStringFromFile(fileName);
- } catch (FileNotFoundException e) {
- System.out.println("Ошибка. Указанный файл не найден.");
- } catch (IOException e) {
- System.out.println("Ошибка. чвми");
- }
- } while (isIncorrectFile);
- return fileName;
- }
- 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 String readString() throws IOException {
- String inStr;
- boolean fileInput = chooseInOutType("in");
- if (fileInput) {
- String inputFileName = readFileName();
- inStr = readStringFromFile(inputFileName);
- } else {
- inStr = readNumberString();
- }
- return inStr;
- }
- static void printToFile(String printStr) throws IOException {
- String outputFileName = chooseOutputFile();
- writelnStrInFile(outputFileName, "Числа, представленные римскими цифрами: ");
- writelnStrInFile(outputFileName, printStr);
- System.out.println("Запись в файл успешно произведена");
- }
- static void printResult(String decStr, String romStr) throws IOException {
- System.out.println("Числа, представленные арабскими цифрами: " + decStr);
- System.out.println("Числа, представленные рисмкими цифрами: " + romStr);
- boolean fileOutput = chooseInOutType("out");
- if (fileOutput) {
- printToFile(romStr);
- }
- }
- public static void main(String[] args) throws IOException {
- System.out.println("Данная программа переводит до 4 введённых чисел, представленных арабскими цифрами, в римскую систему счисления");
- String fullDecStr = readString();
- fullDecStr = deleteExcessSpaces(fullDecStr);
- String fullRomanStr = convertString(fullDecStr);
- printResult(fullDecStr, fullRomanStr);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement