@@ -8,34 +8,35 @@ private MonoAlphabetic() {
8
8
9
9
// Encryption method
10
10
public static String encrypt (String data , String key ) {
11
+ // Validate that the input data contains only uppercase letters
11
12
if (!data .matches ("[A-Z]+" )) {
12
13
throw new IllegalArgumentException ("Input data contains invalid characters. Only uppercase A-Z are allowed." );
13
14
}
14
15
StringBuilder sb = new StringBuilder ();
16
+
17
+ // Convert input data to uppercase
15
18
data = data .toUpperCase ();
16
19
20
+ // Encrypt each character
17
21
for (char c : data .toCharArray ()) {
18
- if (c >= 'A' && c <= 'Z' ) {
19
- int idx = c - 'A' ; // Index in alphabet
20
- sb .append (key .charAt (idx )); // Append the character from the key
21
- }
22
+ int idx = charToPos (c ); // Get the index in the alphabet
23
+ sb .append (key .charAt (idx )); // Append the character from the key
22
24
}
23
25
return sb .toString ();
24
26
}
25
27
26
28
// Decryption method
27
29
public static String decrypt (String data , String key ) {
28
30
StringBuilder sb = new StringBuilder ();
31
+
32
+ // Convert input data to uppercase
29
33
data = data .toUpperCase ();
30
34
35
+ // Decrypt each character
31
36
for (char c : data .toCharArray ()) {
32
- if (c >= 'A' && c <= 'Z' ) {
33
- int idx = charToPos (c );
34
- char originalChar = posToChar (key .indexOf (c ));
35
- sb .append (originalChar );
36
- } else {
37
- sb .append (c ); // Append non-alphabet characters directly
38
- }
37
+ int idx = charToPos (c ); // Get the index in the key
38
+ char decryptedChar = posToChar (key .indexOf (c )); // Find the position in the key and convert back to char
39
+ sb .append (decryptedChar ); // Append the decrypted character
39
40
}
40
41
return sb .toString ();
41
42
}
0 commit comments