-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathAyushee3
73 lines (64 loc) · 2.12 KB
/
Ayushee3
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
//Ayushee Gupta
import java.util.Scanner;
public class CaesarCipher {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("----------Caesar Cipher-----------");
System.out.print("Enter the Message: ");
String msg = scanner.nextLine();
System.out.print("Enter the Position: ");
int position = scanner.nextInt();
String encryptedMsg = Encrypt(msg, position);
String decryptMsg= Decrypt(encryptedMsg, position);
System.out.println("Encrypted Message: " + encryptedMsg);
System.out.println("Decrypted Message: " + decryptMsg );
}
public static String Encrypt(String textToEncrypt, int positions)
{
String toEncrypt = "",
result = "";
for(int i=0; i< textToEncrypt.length(); i++)
{
if(textToEncrypt.charAt(i) == ' ' || textToEncrypt.charAt(i) == '.')
{
continue;
}
else
{
if(Character.isLowerCase(textToEncrypt.charAt(i)))
{
toEncrypt += Character.toUpperCase(textToEncrypt.charAt(i));
}
else
{
toEncrypt += textToEncrypt.charAt(i);
}
}
}
for(int i=0; i<toEncrypt.length(); i++)
{
char shiftedLetter = (char) (toEncrypt.charAt(i)+positions);
if(shiftedLetter>'Z')
{
shiftedLetter = (char) (shiftedLetter - 'Z' + 'A' - 1);
}
result += shiftedLetter;
}
return result;
}
public static String Decrypt(String textToDecrypt, int positions)
{
String result = "";
for(int i=0; i< textToDecrypt.length(); i++)
{
char shiftedLetter = (char) (textToDecrypt.charAt(i)-positions);
if(shiftedLetter<'A')
{
shiftedLetter = (char) (shiftedLetter + 'Z' - 'A' + 1);
}
result += shiftedLetter;
}
return result;
}
}