Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package OAiP;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.Scanner;
- public class Program2 {
- public static void main(String[] args) throws IOException {
- System.out.println("This program encrypt string according to the encoding table.\n");
- Scanner in = new Scanner(System.in);
- String reader[];
- String text = "", st1 = "", st2 = "";
- boolean inValid = true;
- do {
- System.out.println("Enter '1' if you want to load data from console, and '2' from file: ");
- switch (in.nextLine()) {
- case "1":
- reader = loadData();
- text = reader[0];
- st1 = reader[1];
- st2 = reader[2];
- inValid = false;
- break;
- case "2":
- reader = loadDataFromFile();
- text = reader[0];
- st1 = reader[1];
- st2 = reader[2];
- inValid = false;
- break;
- }
- } while (inValid);
- outputData(encrypter(text, st1, st2));
- }
- public static String[] loadDataFromFile() throws IOException {
- Scanner in = new Scanner(System.in);
- FileReader inF = new FileReader("orginal_string.txt");
- Scanner fileScanner = new Scanner(inF);
- boolean inValid = true;
- do {
- try {
- System.out.println("Enter input file directory: ");
- inF = new FileReader(in.nextLine());
- inValid = false;
- } catch (Exception e) {
- System.out.println("File not found");
- }
- } while (inValid);
- String reader[] = new String[3];
- reader[0] = fileScanner.nextLine();
- reader[1] = fileScanner.nextLine();
- reader[2] = fileScanner.nextLine();
- inF.close();
- return reader;
- }
- public static String encrypter(String text, String st1, String st2) {
- for (int i = 0; i < st1.length(); i++) {
- text = text.replaceAll(st1.charAt(i) + "", st2.charAt(i) + "");
- }
- return text;
- }
- public static void outputData(String text) throws IOException {
- Scanner in = new Scanner(System.in);
- System.out.println("Enter output file directory: ");
- FileWriter outF = new FileWriter(in.nextLine());
- System.out.println("Encrypted string: " + text);
- outF.write("Encrypted string: " + text);
- outF.close();
- }
- public static String[] loadData() {
- Scanner in = new Scanner(System.in);
- String reader[] = new String[3];
- System.out.println("Enter string for encrypting: ");
- reader[0] = in.nextLine();
- boolean inValid = true;
- do {
- System.out.println("Enter original string according to encoding table: ");
- reader[1] = in.nextLine();
- System.out.println("Enter final string according to encoding table: ");
- reader[2] = in.nextLine();
- if (reader[1].length() == reader[2].length()) {
- inValid = false;
- } else {
- System.out.println("Input error. Strings must have the same length.");
- }
- } while (inValid);
- return reader;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement