-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcaesar_cipher.java
More file actions
69 lines (68 loc) · 2.1 KB
/
caesar_cipher.java
File metadata and controls
69 lines (68 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.util.Scanner;
public class caesar_cipher {
public static void decrypt(String str,char arr[],int n){
String ct="";
String pt="";
int b;
for(int i=0;i<str.length();i++) {
if (str.charAt(i) == ' ') {
continue;
} else {
ct = ct + str.toLowerCase().charAt(i);
}
}
for(int i=0;i<ct.length();i++) {
for (int j = 0; j < arr.length; j++) {
if (ct.charAt(i) == arr[j]) {
b = (j - n) % 26;
pt = pt + arr[b];
}
}
}
System.out.println(pt);
}
public static void encrypt(String str,char arr[],int n){
String ct="";
String pt="";
int b;
for(int i=0;i<str.length();i++) {
if (str.charAt(i) == ' ') {
continue;
} else {
pt = pt + str.charAt(i);
}
}
for(int i=0;i<pt.length();i++) {
for (int j = 0; j < arr.length; j++) {
if (pt.charAt(i) == arr[j]) {
b = (j + n) % 26;
ct = ct + arr[b];
}
}
}
System.out.println(ct.toUpperCase());
}
public static void main(String args[]) {
char arr[] = {'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'};
int n;
int choice;
String str;
Scanner in = new Scanner(System.in);
System.out.println("enter a string");
str = in.nextLine();
System.out.println("enter the shift");
n = in.nextInt();
System.out.println("1.encrypt 2.decrypt 3.exit");
choice = in.nextInt();
switch (choice) {
case 1:
encrypt(str, arr, n);
break;
case 2:
decrypt(str, arr, n);
break;
default:
break;
}
}
}