Skip to content

Commit f2ccca5

Browse files
authored
Update MonoAlphabetic.java
1 parent eea1c0c commit f2ccca5

File tree

1 file changed

+12
-21
lines changed

1 file changed

+12
-21
lines changed

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

+12-21
Original file line numberDiff line numberDiff line change
@@ -11,41 +11,32 @@ public MonoAlphabetic(String key) {
1111

1212
// Encryption method
1313
public String encrypt(String data) {
14-
int idx;
15-
char c;
1614
StringBuilder sb = new StringBuilder(data.toUpperCase());
1715

1816
for (int i = 0; i < sb.length(); i++) {
19-
idx = sb.charAt(i) - 65; // Subtract ASCII value of 'A' to get index
20-
c = key.charAt(idx); // Find the character at the corresponding key position
21-
sb.setCharAt(i, c); // Replace with the key character
17+
char currentChar = sb.charAt(i);
18+
if (Character.isLetter(currentChar)) { // Check if it's a letter
19+
int index = currentChar - 'A'; // Get the index for the character
20+
sb.setCharAt(i, key.charAt(index)); // Replace with the key character
21+
}
2222
}
2323
return sb.toString();
2424
}
2525

2626
// Decryption method
2727
public String decrypt(String data) {
28-
int idx;
29-
char c;
3028
StringBuilder sb = new StringBuilder(data.toUpperCase());
3129

3230
for (int i = 0; i < sb.length(); i++) {
33-
c = sb.charAt(i); // Get the character from encrypted data
34-
idx = getIndex(c); // Get the corresponding index from the key
35-
c = (char) (idx + 65); // Convert index back to character
36-
sb.setCharAt(i, c); // Replace with the original character
37-
}
38-
return sb.toString();
39-
}
40-
41-
// Helper method to get index of a character in the key
42-
private int getIndex(char c) {
43-
for (int i = 0; i < key.length(); i++) {
44-
if (key.charAt(i) == c) {
45-
return i; // Return the index if the character matches
31+
char currentChar = sb.charAt(i);
32+
if (Character.isLetter(currentChar)) { // Check if it's a letter
33+
int index = key.indexOf(currentChar); // Find the character in the key
34+
if (index != -1) {
35+
sb.setCharAt(i, (char) (index + 'A')); // Replace with the original character
36+
}
4637
}
4738
}
48-
return -1; // Return -1 if character not found (should not happen for valid inputs)
39+
return sb.toString();
4940
}
5041

5142
// Static utility methods for encryption/decryption without creating an instance

0 commit comments

Comments
 (0)