Advertisement
Guest User

Untitled

a guest
Jul 15th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. import java.io.FileNotFoundException;
  2. import java.io.FileReader;
  3. import java.io.PrintWriter;
  4. import java.util.HashMap;
  5. import java.util.Map.Entry;
  6. import java.util.Scanner;
  7.  
  8. // Make an application which reads a file 1 byte at a time and encrypts it based on
  9. // the algorithm covered in the lecture notes and writes the result to another file
  10. // Then send me the file and encryption key and I'll decrypt it to see if you did it correctly
  11.  
  12. public class CaesarCypher {
  13. public static HashMap<String, Integer> alphabet = new HashMap<String, Integer>();
  14. public static void alphabetMap() {
  15. // String alpha = "abcdefghijklmnopqrstuvwxyz";
  16. alphabet.put("a", 1);
  17. alphabet.put("b", 2);
  18. alphabet.put("c", 3);
  19. alphabet.put("d", 4);
  20. alphabet.put("e", 5);
  21. alphabet.put("f", 6);
  22. alphabet.put("g", 7);
  23. alphabet.put("h", 8);
  24. alphabet.put("i", 9);
  25. alphabet.put("j", 10);
  26. alphabet.put("k", 11);
  27. alphabet.put("l", 12);
  28. alphabet.put("m", 13);
  29. alphabet.put("n", 14);
  30. alphabet.put("o", 15);
  31. alphabet.put("p", 16);
  32. alphabet.put("q", 17);
  33. alphabet.put("r", 18);
  34. alphabet.put("s", 19);
  35. alphabet.put("t", 20);
  36. alphabet.put("u", 21);
  37. alphabet.put("v", 22);
  38. alphabet.put("w", 23);
  39. alphabet.put("x", 24);
  40. alphabet.put("y", 25);
  41. alphabet.put("z", 26);
  42. }
  43.  
  44. public static void main(String[] args) {
  45. FileReader myFileReader;
  46. try {
  47. Integer key = 3; //value must be 1-25
  48. myFileReader = new FileReader("input.txt");
  49. Scanner myScanner = new Scanner(myFileReader).useDelimiter("[a-zA-Z]");
  50. PrintWriter myPrintWriter = new PrintWriter("output.txt");
  51.  
  52. while (myScanner.hasNext()) {
  53. String letter = myScanner.next();
  54. Integer index = alphabet.get(letter); //new letter's position in alphabet
  55.  
  56. if (key + index > 26) { //If moving this letter would go beyond alphabet
  57. index = index + key - 26;
  58. }
  59. else {
  60. index = index + key;
  61. }
  62.  
  63. for (Entry<String, Integer> entry : alphabet.entrySet()) { //Get letter found at new position
  64. if (entry.getValue().equals(index)) {
  65. myPrintWriter.write(alphabet.get(entry.getKey()));
  66. }
  67. }
  68.  
  69. // myPrintWriter.print(alphabet.get(index));
  70. }
  71.  
  72. myScanner.close();
  73. myPrintWriter.close();
  74. }
  75.  
  76. catch (FileNotFoundException e) {
  77. e.printStackTrace();
  78. }
  79. }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement