-
Notifications
You must be signed in to change notification settings - Fork 0
/
CaesarCipher.java
50 lines (43 loc) · 1.09 KB
/
CaesarCipher.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
package com.test.done;
public class CaesarCipher {
public static void main(String[] args) {
String str = "z";
int k = 2;
caesarCipher(str, k);
}
public static String caesarCipher(String s, int k) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
int num = (s.charAt(i));
if (num >= 97 && num <= 122) {
if (num + k > 122) {
num = ((num + k - 122)) + 96;
System.out.println(num);
num = ((num - 97 + k) % 26) + 97;
System.out.println(num);
} else {
num = num + k;
}
char x = (char) num;
result.append(x);
} else if (num >= 65 && num <= 90) {
if (num + k > 90) {
num = ((num + k - 90) % 26) + 64;
// char x = (char) num;
System.out.println(num);
num = ((num - 65 + k) % 26) + 65;
System.out.println(num);
} else {
num = num + k;
}
char x = (char) num;
result.append(x);
} else {
char x = (char) num;
result.append(x);
}
}
// System.out.println(result.toString());
return result.toString();
}
}