@@ -11,41 +11,32 @@ public MonoAlphabetic(String key) {
11
11
12
12
// Encryption method
13
13
public String encrypt (String data ) {
14
- int idx ;
15
- char c ;
16
14
StringBuilder sb = new StringBuilder (data .toUpperCase ());
17
15
18
16
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
+ }
22
22
}
23
23
return sb .toString ();
24
24
}
25
25
26
26
// Decryption method
27
27
public String decrypt (String data ) {
28
- int idx ;
29
- char c ;
30
28
StringBuilder sb = new StringBuilder (data .toUpperCase ());
31
29
32
30
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
+ }
46
37
}
47
38
}
48
- return - 1 ; // Return -1 if character not found (should not happen for valid inputs)
39
+ return sb . toString ();
49
40
}
50
41
51
42
// Static utility methods for encryption/decryption without creating an instance
0 commit comments