-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCaesarCipherProgram.java
48 lines (44 loc) · 1.69 KB
/
CaesarCipherProgram.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
import java.util.*;
public class CaesarCipherProgram {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println(" Input the plaintext message : ");
String plaintext = sc.nextLine();
System.out.println(" Enter the value by which each character in the plaintext message gets shifted : ");
int shift = sc.nextInt();
String ciphertext = "";
char alphabet;
for(int i=0; i < plaintext.length();i++)
{
// Shift one character at a time
alphabet = plaintext.charAt(i);
// if alphabet lies between a and z
if(alphabet >= 'a' && alphabet <= 'z')
{
// shift alphabet
alphabet = (char) (alphabet + shift);
// if shift alphabet greater than 'z'
if(alphabet > 'z') {
// reshift to starting position
alphabet = (char) (alphabet+'a'-'z'-1);
}
ciphertext = ciphertext + alphabet;
}
// if alphabet lies between 'A'and 'Z'
else if(alphabet >= 'A' && alphabet <= 'Z') {
// shift alphabet
alphabet = (char) (alphabet + shift);
// if shift alphabet greater than 'Z'
if(alphabet > 'Z') {
//reshift to starting position
alphabet = (char) (alphabet+'A'-'Z'-1);
}
ciphertext = ciphertext + alphabet;
}
else {
ciphertext = ciphertext + alphabet;
}
}
System.out.println(" ciphertext : " + ciphertext);
}
}