Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.*;
- public class Encryptor
- {
- private final static int NUM_LETTERS = 25;
- 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'};
- public String encrypt(int key, String msg){
- msg = msg.toLowerCase();
- char[] charMsg = msg.toCharArray();
- ArrayList<Character> newMsg = new ArrayList<Character>();
- for(int i=0; i<charMsg.length; i++){
- if(charMsg[i] == ' '){
- newMsg.add(' ');
- }
- for(int x = 0; x < this.abc.length; x++){
- if(charMsg[i] == this.abc[x]){
- if(x + key > NUM_LETTERS){
- int diff = x+key-NUM_LETTERS;
- x = diff-4;
- }
- newMsg.add(this.abc[x+key]);
- break;
- }
- }
- }
- StringBuilder builder = new StringBuilder(newMsg.size());
- for(Character ch: newMsg)
- {
- builder.append(ch);
- }
- return builder.toString();
- }
- public String decrypt(int key, String msg){
- char[] charMsg = msg.toCharArray();
- ArrayList<Character> newMsg = new ArrayList<Character>();
- for(int i=0; i<charMsg.length; i++){
- if(charMsg[i] == ' '){
- newMsg.add(' ');
- }
- for(int x = 0; x < this.abc.length; x++){
- if(charMsg[i] == this.abc[x]){
- if(x - key < 0){
- x = NUM_LETTERS+(x-key+1);
- newMsg.add(this.abc[x]);
- break;
- }
- newMsg.add(this.abc[x-key]);
- break;
- }
- }
- }
- StringBuilder builder = new StringBuilder(newMsg.size());
- for(Character ch: newMsg)
- {
- builder.append(ch);
- }
- return builder.toString();
- }
- public static void main(String[] args)
- {
- Scanner scan = new Scanner(System.in);
- Encryptor e = new Encryptor();
- System.out.println("Enter your message");
- String encryptedMsg = e.encrypt(3, scan.nextLine());
- System.out.println(encryptedMsg);
- System.out.println(e.decrypt(3, encryptedMsg));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement