-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathINS_P2.java
More file actions
74 lines (61 loc) · 1.79 KB
/
Copy pathINS_P2.java
File metadata and controls
74 lines (61 loc) · 1.79 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
70
71
72
73
74
package ins;
import java.util.Scanner;
/**
*
* @author Raj Dhanani
*/
class Caesar {
//a-97
//z-122
//A-65
//Z-90
String plainText = "";
String cipherText = "";
int key;
Caesar() {
}
Caesar(String plainText, int key) {
this.plainText = plainText;
this.key = key;
encrypt();
}
void encrypt() {
for (int i = 0; i < plainText.length(); i++) {
char p = plainText.charAt(i);
if (p >= 'A' && p <= 'Z') {
cipherText += (char) (((p - 65) + key) % 26 + 65);
} else if (p >= 'a' && p <= 'z') {
cipherText += (char) (((p - 97) + key) % 26 + 97);
} else {
cipherText += p;
}
}
}
String decrypt(String cipherText, int key) {
String pT = "";
int c, t;
for (int i = 0; i < cipherText.length(); i++) {
c = cipherText.charAt(i);
if (c >= 'a' && c <= 'z') {
pT += (char) ((((t = (c - 'a' - key) % 26) < 0) ? t + 26 : t) + 'a');
} else if (c >= 'A' && c <= 'Z') {
pT += (char) ((((t = (c - 'A' - key) % 26) < 0) ? t + 26 : t) + 'A');
} else {
pT += (char) c;
}
}
return pT;
}
}
public class INS_P2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter String:");
String input = in.nextLine();
System.out.println("Enter key:");
int key = in.nextInt();
Caesar c = new Caesar(input, key);
System.out.println("Cipher:" + c.cipherText);
System.out.println("Decripted:" + c.decrypt(c.cipherText, c.key));
}
}