Advertisement
Guest User

Untitled

a guest
Jan 20th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.*;
  3.  
  4. public class Encryptor
  5. {
  6. private final static int NUM_LETTERS = 25;
  7. private char[] abc = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
  8. public String encrypt(int key, String msg){
  9. msg = msg.toLowerCase();
  10. char[] charMsg = msg.toCharArray();
  11. ArrayList<Character> newMsg = new ArrayList<Character>();
  12. for(int i=0; i<charMsg.length; i++){
  13. if(charMsg[i] == ' '){
  14. newMsg.add(' ');
  15. }
  16. for(int x = 0; x < this.abc.length; x++){
  17. if(charMsg[i] == this.abc[x]){
  18. if(x + key > NUM_LETTERS){
  19. int diff = x+key-NUM_LETTERS;
  20. x = diff-4;
  21. }
  22. newMsg.add(this.abc[x+key]);
  23. break;
  24. }
  25. }
  26. }
  27.  
  28. StringBuilder builder = new StringBuilder(newMsg.size());
  29. for(Character ch: newMsg)
  30. {
  31. builder.append(ch);
  32. }
  33. return builder.toString();
  34.  
  35. }
  36.  
  37. public String decrypt(int key, String msg){
  38. char[] charMsg = msg.toCharArray();
  39. ArrayList<Character> newMsg = new ArrayList<Character>();
  40. for(int i=0; i<charMsg.length; i++){
  41. if(charMsg[i] == ' '){
  42. newMsg.add(' ');
  43. }
  44. for(int x = 0; x < this.abc.length; x++){
  45. if(charMsg[i] == this.abc[x]){
  46. if(x - key < 0){
  47. x = NUM_LETTERS+(x-key+1);
  48.  
  49. newMsg.add(this.abc[x]);
  50. break;
  51. }
  52.  
  53. newMsg.add(this.abc[x-key]);
  54. break;
  55. }
  56. }
  57. }
  58.  
  59. StringBuilder builder = new StringBuilder(newMsg.size());
  60. for(Character ch: newMsg)
  61. {
  62. builder.append(ch);
  63. }
  64. return builder.toString();
  65. }
  66.  
  67. public static void main(String[] args)
  68. {
  69. Scanner scan = new Scanner(System.in);
  70.  
  71. Encryptor e = new Encryptor();
  72. System.out.println("Enter your message");
  73. String encryptedMsg = e.encrypt(3, scan.nextLine());
  74. System.out.println(encryptedMsg);
  75. System.out.println(e.decrypt(3, encryptedMsg));
  76.  
  77.  
  78.  
  79.  
  80. }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement