Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Java программирование > Общие вопросы по Java, Java SE, Kotlin
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 19.12.2018, 14:12   #1
Nastya2018
Форумчанин
 
Регистрация: 24.07.2018
Сообщений: 133
По умолчанию Ошибка в коде

Ребята почему у меня не работает код. Он должен открыть файл (xml или тхт) и в нем кириллицу конвертировать в латиницу. И после конвертирования сохранить его в новый файл

Код:
import java.io.*;
import java.util.*;
 
public class Main {
    public static void main(String[] args) throws IOException{
        String inputFilePath = "C:\\Users\\Nastya\\Desktop\\Первый перевод\\strings2a_kz.txt";
        String outputFilePath = "C:\\Users\\Nastya\\Desktop\\Первый перевод\\output.txt";
 
        FileReader fileReader = new FileReader(inputFilePath);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        FileWriter fileWriter = new FileWriter(outputFilePath);
 
        String line;
        StringBuilder result = new StringBuilder();
 
        Map<Character, Character> dictionary = new Dictionary().getDictionary();
 
        while ((line = bufferedReader.readLine()) != null) {
            result.append(convertString(line, dictionary) + System.getProperty("line.separator")) ;
        }
 
        bufferedReader.close();
        fileReader.close();
 
        fileWriter.write(result.toString());
        fileWriter.flush();
        fileWriter.close();
    }
 
    public static String convertString(String str, Map<Character, Character> dictionary) {
        char[] chars = str.toCharArray();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            if (dictionary.containsKey(chars[i])) {
                stringBuilder.append(dictionary.get(chars[i]));
                continue;
            }
            stringBuilder.append(chars[i]);
        }
        return stringBuilder.toString();
    }
}
 
class Dictionary {
    private Map<Character, Character> dictionary;
 
    public Dictionary() {
        dictionary = new HashMap<>();
        dictionary.put('а', 'a');
        dictionary.put('ә', 'a');
        dictionary.put('б', 'b');
        dictionary.put('д', 'd');
        dictionary.put('е', 'e');
        dictionary.put('ф', 'f');
        dictionary.put('г', 'g');
        dictionary.put('ғ', 'g');
        dictionary.put('х', 'h');
        dictionary.put('h', 'h');
        dictionary.put('і', 'i');
        dictionary.put('и', 'i');
        dictionary.put('й', 'i');
        dictionary.put('ж', 'j');
        dictionary.put('к', 'k');
        dictionary.put('л', 'l');
        dictionary.put('м', 'm');
        dictionary.put('н', 'n');
        dictionary.put('ң', 'n');
        dictionary.put('о', 'o');
        dictionary.put('ө', 'o');
        dictionary.put('п', 'p');
        dictionary.put('қ', 'q');
        dictionary.put('р', 'r');
        dictionary.put('с', 's');
        dictionary.put('ш', 's');
        dictionary.put('ч', 'c');
        dictionary.put('т', 't');
        dictionary.put('ү', 'u');
        dictionary.put('ұ', 'u');
        dictionary.put('в', 'v');
        dictionary.put('ы', 'y');
        dictionary.put('у', 'y');
        dictionary.put('з', 'z');
    }
 
    public Map<Character, Character> getDictionary() {
        return dictionary;
    }
}
Nastya2018 вне форума Ответить с цитированием
Старый 19.12.2018, 21:37   #2
JavaDoc
Пользователь
 
Регистрация: 15.12.2018
Сообщений: 16
По умолчанию

Ты получаешь чар и сравниваешь через контейнс я бы сплитом разбил на символы... Получил бы массив стринга из символов
JavaDoc вне форума Ответить с цитированием
Старый 19.12.2018, 21:40   #3
JavaDoc
Пользователь
 
Регистрация: 15.12.2018
Сообщений: 16
По умолчанию

Код плохо читается вернись к основам ооп
JavaDoc вне форума Ответить с цитированием
Старый 19.12.2018, 21:41   #4
JavaDoc
Пользователь
 
Регистрация: 15.12.2018
Сообщений: 16
По умолчанию

А то вроде написано то три строчки а не знаешь куда смотреть...
JavaDoc вне форума Ответить с цитированием
Старый 20.12.2018, 06:30   #5
Nastya2018
Форумчанин
 
Регистрация: 24.07.2018
Сообщений: 133
По умолчанию

Почему он у меня не может найти указанный файл.

И вот такая ошибка
Код:
Exception in thread "main" java.io.FileNotFoundException: C:\Users\Nastya\Desktop\Первый перевод\strings2a_kz.txt (Не удается найти указанный файл)
	at java.io.FileInputStream.open0(Native Method)
	at java.io.FileInputStream.open(FileInputStream.java:195)
	at java.io.FileInputStream.<init>(FileInputStream.java:138)
	at java.io.FileInputStream.<init>(FileInputStream.java:93)
	at java.io.FileReader.<init>(FileReader.java:58)
	at Main.main(Main.java:9)
Код:
import java.io.*;
import java.util.*;
 
public class Main {
    public static void main(String[] args) throws IOException{
        String inputFilePath = "C:\\Users\\Nastya\\Desktop\\Первый перевод\\strings2a_kz.txt";
        String outputFilePath = "C:\\Users\\Nastya\\Desktop\\Первый перевод\\output.txt";
 
        FileReader fileReader = new FileReader(inputFilePath);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        FileWriter fileWriter = new FileWriter(outputFilePath);
 
        String line;
        StringBuilder result = new StringBuilder();
 
        Map<String, String> dictionary = new Dictionary().getDictionary();
 
        while ((line = bufferedReader.readLine()) != null) {
            result.append(convertString(line, dictionary) + System.getProperty("line.separator")) ;
        }
 
        bufferedReader.close();
        fileReader.close();
 
        fileWriter.write(result.toString());
        fileWriter.flush();
        fileWriter.close();
    }
 
    public static String convertString(String str, Map<String, String> dictionary) {
        char[] chars = str.toCharArray();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            if (dictionary.containsKey(chars[i])) {
                stringBuilder.append(dictionary.get(chars[i]));
                continue;
            }
            stringBuilder.append(chars[i]);
        }
        return stringBuilder.toString();
    }
}
 
class Dictionary {
    private Map<String, String> dictionary;
 
    public Dictionary() {
        dictionary = new HashMap<>();
        dictionary.put("а", "a");
        dictionary.put("А", "А");
        dictionary.put("ә", "á");
        dictionary.put("Ә", "Á");
        dictionary.put("б", "b");
        dictionary.put("Б", "B");
        dictionary.put("д", "d");
        dictionary.put("Д", "D");
        dictionary.put("е", "e");
        dictionary.put("E", "E");
        dictionary.put("ф", "f");
        dictionary.put("Ф", "F");
        dictionary.put("г", "g");
        dictionary.put("Г", "G");
        dictionary.put("ғ", "ǵ");
        dictionary.put("Ғ", "Ǵ");        
        dictionary.put("х", "h");
        dictionary.put("Х", "H");
        dictionary.put("h", "һ");
        dictionary.put("Һ", "Һ");
        dictionary.put("і", "i");
        dictionary.put("І", "І");
        dictionary.put("и", "ı");
        dictionary.put("И", "I");
        dictionary.put("й", "i");
        dictionary.put("Й", "I");
        dictionary.put("ж", "j");
        dictionary.put("Ж", "J");
        dictionary.put("к", "k");
        dictionary.put("К", "К");
        dictionary.put("л", "l");
        dictionary.put("Л", "L");
        dictionary.put("м", "m");
        dictionary.put("М", "M");
        dictionary.put("н", "n");
        dictionary.put("Н", "N");
        dictionary.put("ң", "ń");
        dictionary.put("Ң", "Ń");
        dictionary.put("о", "o");
        dictionary.put("О", "О");
        dictionary.put("ө", "ó");
        dictionary.put("Ө", "Ó");
        dictionary.put("п", "p");
        dictionary.put("П", "P");
        dictionary.put("қ", "q");
        dictionary.put("Қ", "Q");
        dictionary.put("р", "r");
        dictionary.put("Р", "R");
        dictionary.put("с", "s");
        dictionary.put("С", "S");
        dictionary.put("ш", "sh");
        dictionary.put("Ш", "Sh");
        dictionary.put("ч", "ch");
        dictionary.put("Ч", "Сh");
        dictionary.put("т", "t");
        dictionary.put("Т", "T");
        dictionary.put("ү", "ú");
        dictionary.put("Ү", "Ú");
        dictionary.put("ұ", "u");
        dictionary.put("Ұ", "U");
        dictionary.put("в", "v");
        dictionary.put("В", "V");
        dictionary.put("ы", "y");
        dictionary.put("Ы", "Y");
        dictionary.put("у", "ý");
        dictionary.put("У", "Ý");
        dictionary.put("з", "z");
        dictionary.put("З", "Z");
    }
 
    public Map<String, String> getDictionary() {
        return dictionary;
    }
}
Nastya2018 вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Java. Ошибка. Компилируется, но не запускается. Ошибка duplicate class. Проблема не в коде. nevender Общие вопросы по Java, Java SE, Kotlin 2 13.02.2016 13:24
Ошибка в коде devtriker Помощь студентам 5 14.10.2014 21:02
Ошибка в коде Dima9595 Паскаль, Turbo Pascal, PascalABC.NET 2 11.04.2014 16:49
Где ошибка в этом исходном коде на языке Си? Или ошибка в Excel? ArchiCurtis Помощь студентам 2 07.04.2012 14:16
Ошибка в коде, ошибка в css или это проблема с совместимостью с браузерами? ankris HTML и CSS 5 23.11.2010 16:58