-
Notifications
You must be signed in to change notification settings - Fork 0
/
Caesar.java
52 lines (47 loc) · 1.27 KB
/
Caesar.java
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
import java.util.Scanner;
public class Caesar {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the key: ");
int key = in.nextInt();
in.nextLine();
System.out.print("Enter the message: ");
String s = in.nextLine();
char[] a = s.toCharArray(); // converting string to char array
int n = a.length;
char[] b = new char[n];
for (int i = 0; i < n; i++) {
char c = a[i];
int num = c;
if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122)) {
if (c >= 65 && c <= 90) { // checking if it is uppercase
int newkey = num + key; // adding key given
if (newkey > 90) { // checking if its out of range
while(newkey > 90) {
newkey = (newkey - 90) + 64; // rotating the digit for ex: if letter z and key is 2 then new letter is b
}
b[i] = (char) (newkey);
} else {
b[i] = (char) (newkey);
}
} else if (c >= 97 && c <= 122) {
int newkey = (num + key);
if (newkey > 122) {
while(newkey > 122) {
newkey = (newkey - 122) + 96;
}
b[i] = (char) (newkey);
} else {
b[i] = (char) (newkey);
}
}
} else {
b[i] = c;
}
}
System.out.print("Encrypted message: ");
for (char c : b) {
System.out.print(c);
}
}
}