Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/main/java/com/javarush/baeramshina/ConsoleReader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.javarush.baeramshina;

import java.util.Scanner;

public class ConsoleReader extends InputReader {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это правильно сделано

private final Scanner console;

public ConsoleReader(Scanner console){
this.console=console;
}

@Override
public String readInput() {
System.out.println("Введите текст: ");
return console.nextLine();
}
}
108 changes: 108 additions & 0 deletions src/main/java/com/javarush/baeramshina/ConsoleRunner.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package com.javarush.baeramshina;

import java.util.Map;
import java.util.Scanner;

import static com.javarush.baeramshina.Decrypt.decryptText;
import static com.javarush.baeramshina.Encrypt.encryptText;


public class ConsoleRunner {
private static String originalText = null;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А вот это неправильно. Во-первых поля и так пустые, а во-вторых статически их делают очень редко

private static String encryptedText = null;
private static String decryptedText = null;


public static void main(String[] args) {

Scanner console = new Scanner(System.in);
MenuOption selectedOption;

while (true) {
MenuOption.printMenu();

String input = console.nextLine();
try {
int optionNumber = Integer.parseInt(input);
selectedOption = MenuOption.getOptionByNumber(optionNumber);
if (selectedOption == null) {
System.out.println("Некорректный выбор, попробуйте еще.");
continue;
}
switch (selectedOption) {

case READ_CONSOLE:
handleReadConsole(console);
break;
case READ_FILE:
handleReadFile(console);
break;
case ENCRYPT:
handleEncrypt();
break;
case DECRYPT:
handleDecrypt();
break;
case WRITE_FILE:
handleWriteFile();
break;
case EXIT:
System.out.println("Выход");
break;
default:

break;
}

} catch (NumberFormatException e) {
System.out.println("Пожалуйста, введите число.");
}
}
}


private static void handleReadFile(Scanner console) {
InputReader readFile = new ReadFile("text/dict.txt");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут плохо то что путь к файлу указан жёстко

String fileContent = readFile.readInput();
if (fileContent != null) {
originalText = fileContent;
System.out.println("Текст прочитан" + originalText);
} else {
System.out.println("Файл пуст или не найден");

}
}

private static void handleReadConsole(Scanner console) {
InputReader consoleReader = new ConsoleReader(console);
String readInput = consoleReader.readInput();
if (readInput != null) {
originalText = readInput;
System.out.println("Текс введен: " + originalText);
} else {
System.out.println("Текст отсутствует");
}
}

private static void handleEncrypt() {

Map<Character, Character> caesarCipher = LogicEncrypted.createCaesarCipher(5);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что такое пять догадаться сложно

encryptedText = encryptText(originalText, caesarCipher);
System.out.println("Зашифрованный текст " + encryptedText);
}
private static void handleWriteFile(){
WriteFile.writeToFile(encryptedText, "text/encrypt.txt");
System.out.println("Зашифрованный текст записан в файл ext/encrypt.txt");}

private static void handleDecrypt() {

Map<Character, Character> deCipher = LogicDecrypted.cancelsCaesarCipher(5);
decryptedText = decryptText(encryptedText, deCipher);
System.out.println("Расшифрованный текст " + decryptedText);


}
}



24 changes: 24 additions & 0 deletions src/main/java/com/javarush/baeramshina/Decrypt.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.javarush.baeramshina;

import java.util.Map;

public class Decrypt {
public static String decryptText(String text, Map<Character, Character> cipherMap) {
StringBuilder result = new StringBuilder();
for (char c : text.toCharArray()) {
if (cipherMap.containsKey(c)) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Насколько я вижу метод шифрования от метода дешифрования почти не отличается, в таких случаях их лучше объединить в какой-либо абстракции

result.append(cipherMap.get(c));
} else {
result.append(c);
}
}
return result.toString();
}
}







20 changes: 20 additions & 0 deletions src/main/java/com/javarush/baeramshina/Encrypt.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.javarush.baeramshina;

import java.util.Map;

public class Encrypt {
public static String encryptText(String text, Map<Character, Character> cipherMap) {
StringBuilder result = new StringBuilder();
for (char c : text.toCharArray()) {
if (cipherMap.containsKey(c)) {
result.append(cipherMap.get(c));
} else {
result.append(c);
}
}
return result.toString();
}
}



5 changes: 5 additions & 0 deletions src/main/java/com/javarush/baeramshina/InputReader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.javarush.baeramshina;

public abstract class InputReader {
public abstract String readInput();
}
25 changes: 25 additions & 0 deletions src/main/java/com/javarush/baeramshina/LogicDecrypted.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.javarush.baeramshina;

import java.util.HashMap;
import java.util.Map;

public class LogicDecrypted {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь тоже самое

public static Map<Character, Character> cancelsCaesarCipher(int shift) {
Map<Character, Character> map = new HashMap<>();
int length = Symbols.symbols.length;

for (int i = 0; i < length; i++) {
char original = Symbols.symbols[i];
int shiftIndex = (i - shift + length) % length;

char decrypt = Symbols.symbols[shiftIndex];
map.put(original, decrypt);


}

return map;
}


}
27 changes: 27 additions & 0 deletions src/main/java/com/javarush/baeramshina/LogicEncrypted.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.javarush.baeramshina;

import java.util.HashMap;
import java.util.Map;

public class LogicEncrypted {
public static Map<Character, Character> createCaesarCipher(int shift) {
Map<Character, Character> map = new HashMap<>();
int length = Symbols.symbols.length;

for (int i = 0; i < length; i++) {
char original = Symbols.symbols[i];
int shiftIndex = (i + shift) % length;
if (shiftIndex < 0) {
shiftIndex += length;
}
char encrypt = Symbols.symbols[shiftIndex];
map.put(original, encrypt);


}

return map;
}

}

37 changes: 37 additions & 0 deletions src/main/java/com/javarush/baeramshina/MenuOption.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.javarush.baeramshina;

public enum MenuOption {
READ_CONSOLE("Прочитать с консоли"),
READ_FILE("Прочитать файл"),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут видим четыре отдельных команды что в целом неплохо

ENCRYPT("Зашифровать текст"),
DECRYPT("Расшифровать текст"),
WRITE_FILE("Записать зашифрованный текст в отдельный файл"),
EXIT("Выход");

private final String description;

MenuOption(String description) {
this.description = description;
}

public String getDescription() {
return description;
}

public static void printMenu() {
System.out.println("\nВыберите действие:");
for (MenuOption value : MenuOption.values()) {
System.out.println((value.ordinal() + 1) + ". " + value.getDescription());
}
System.out.println("Вы выбрали: ");

}
public static MenuOption getOptionByNumber(int number){
MenuOption[] options = MenuOption.values();
if (number > 0 && number <= options.length) {
return options[number-1];
}
return null;
}
}

35 changes: 35 additions & 0 deletions src/main/java/com/javarush/baeramshina/ReadFile.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.javarush.baeramshina;

import java.io.BufferedReader;

import java.io.FileReader;
import java.io.IOException;

public class ReadFile extends InputReader {
private final String filePath;

public ReadFile(String filePath) {
this.filePath = filePath;
}

@Override
public String readInput() {

StringBuilder info = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while((line =reader.readLine())!=null)

{
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут что-то не то c форматированием

info.append(line).append("\n");

System.out.println(line);
}
} catch(IOException e) {
System.out.println("Ошибка при чтении файла!!!");

e.printStackTrace();
}
return info.toString().trim();
}
}
13 changes: 13 additions & 0 deletions src/main/java/com/javarush/baeramshina/Symbols.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.javarush.baeramshina;

public class Symbols {
public static final char[] symbols = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя.,' '«»:!?1234567890".toCharArray();

public static void printSymbols() {
for (char c : symbols) {
System.out.print(c + " ");
}
System.out.println();
}
}

17 changes: 17 additions & 0 deletions src/main/java/com/javarush/baeramshina/WriteFile.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.javarush.baeramshina;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFile {
public static void writeToFile(String text, String filePath){
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath))){
bufferedWriter.write(text);
System.out.println("Текст успешно записан: "+filePath);
}
catch (IOException e){
System.out.println("Ошибка при записи файла");
}
}
}