Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.PrintWriter;
- import java.util.HashMap;
- import java.util.Map.Entry;
- import java.util.Scanner;
- // Make an application which reads a file 1 byte at a time and encrypts it based on
- // the algorithm covered in the lecture notes and writes the result to another file
- // Then send me the file and encryption key and I'll decrypt it to see if you did it correctly
- public class CaesarCypher {
- public static HashMap<String, Integer> alphabet = new HashMap<String, Integer>();
- public static void alphabetMap() {
- // String alpha = "abcdefghijklmnopqrstuvwxyz";
- alphabet.put("a", 1);
- alphabet.put("b", 2);
- alphabet.put("c", 3);
- alphabet.put("d", 4);
- alphabet.put("e", 5);
- alphabet.put("f", 6);
- alphabet.put("g", 7);
- alphabet.put("h", 8);
- alphabet.put("i", 9);
- alphabet.put("j", 10);
- alphabet.put("k", 11);
- alphabet.put("l", 12);
- alphabet.put("m", 13);
- alphabet.put("n", 14);
- alphabet.put("o", 15);
- alphabet.put("p", 16);
- alphabet.put("q", 17);
- alphabet.put("r", 18);
- alphabet.put("s", 19);
- alphabet.put("t", 20);
- alphabet.put("u", 21);
- alphabet.put("v", 22);
- alphabet.put("w", 23);
- alphabet.put("x", 24);
- alphabet.put("y", 25);
- alphabet.put("z", 26);
- }
- public static void main(String[] args) {
- FileReader myFileReader;
- try {
- Integer key = 3; //value must be 1-25
- myFileReader = new FileReader("input.txt");
- Scanner myScanner = new Scanner(myFileReader).useDelimiter("[a-zA-Z]");
- PrintWriter myPrintWriter = new PrintWriter("output.txt");
- while (myScanner.hasNext()) {
- String letter = myScanner.next();
- Integer index = alphabet.get(letter); //new letter's position in alphabet
- if (key + index > 26) { //If moving this letter would go beyond alphabet
- index = index + key - 26;
- }
- else {
- index = index + key;
- }
- for (Entry<String, Integer> entry : alphabet.entrySet()) { //Get letter found at new position
- if (entry.getValue().equals(index)) {
- myPrintWriter.write(alphabet.get(entry.getKey()));
- }
- }
- // myPrintWriter.print(alphabet.get(index));
- }
- myScanner.close();
- myPrintWriter.close();
- }
- catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement