Skip to content

Commit 8ffc13b

Browse files
authored
Update MonoAlphabetic.java
1 parent cad2f32 commit 8ffc13b

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

src/main/java/com/thealgorithms/ciphers/MonoAlphabetic.java

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,34 +8,35 @@ private MonoAlphabetic() {
88

99
// Encryption method
1010
public static String encrypt(String data, String key) {
11+
// Validate that the input data contains only uppercase letters
1112
if (!data.matches("[A-Z]+")) {
1213
throw new IllegalArgumentException("Input data contains invalid characters. Only uppercase A-Z are allowed.");
1314
}
1415
StringBuilder sb = new StringBuilder();
16+
17+
// Convert input data to uppercase
1518
data = data.toUpperCase();
1619

20+
// Encrypt each character
1721
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
2224
}
2325
return sb.toString();
2426
}
2527

2628
// Decryption method
2729
public static String decrypt(String data, String key) {
2830
StringBuilder sb = new StringBuilder();
31+
32+
// Convert input data to uppercase
2933
data = data.toUpperCase();
3034

35+
// Decrypt each character
3136
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
3940
}
4041
return sb.toString();
4142
}

0 commit comments

Comments
 (0)