9
9
* @author khalil2535
10
10
*/
11
11
public class Caesar {
12
+ private static char normalizeShift (final int shift ) {
13
+ return (char ) (shift % 26 );
14
+ }
12
15
13
16
/**
14
17
* Encrypt text by shifting every Latin char by add number shift for ASCII
@@ -19,7 +22,7 @@ public class Caesar {
19
22
public String encode (String message , int shift ) {
20
23
StringBuilder encoded = new StringBuilder ();
21
24
22
- shift %= 26 ;
25
+ final char shiftChar = normalizeShift ( shift ) ;
23
26
24
27
final int length = message .length ();
25
28
for (int i = 0 ; i < length ; i ++) {
@@ -29,10 +32,10 @@ public String encode(String message, int shift) {
29
32
char current = message .charAt (i ); // Java law : char + int = char
30
33
31
34
if (isCapitalLatinLetter (current )) {
32
- current += shift ;
35
+ current += shiftChar ;
33
36
encoded .append ((char ) (current > 'Z' ? current - 26 : current )); // 26 = number of latin letters
34
37
} else if (isSmallLatinLetter (current )) {
35
- current += shift ;
38
+ current += shiftChar ;
36
39
encoded .append ((char ) (current > 'z' ? current - 26 : current )); // 26 = number of latin letters
37
40
} else {
38
41
encoded .append (current );
@@ -50,16 +53,16 @@ public String encode(String message, int shift) {
50
53
public String decode (String encryptedMessage , int shift ) {
51
54
StringBuilder decoded = new StringBuilder ();
52
55
53
- shift %= 26 ;
56
+ final char shiftChar = normalizeShift ( shift ) ;
54
57
55
58
final int length = encryptedMessage .length ();
56
59
for (int i = 0 ; i < length ; i ++) {
57
60
char current = encryptedMessage .charAt (i );
58
61
if (isCapitalLatinLetter (current )) {
59
- current -= shift ;
62
+ current -= shiftChar ;
60
63
decoded .append ((char ) (current < 'A' ? current + 26 : current )); // 26 = number of latin letters
61
64
} else if (isSmallLatinLetter (current )) {
62
- current -= shift ;
65
+ current -= shiftChar ;
63
66
decoded .append ((char ) (current < 'a' ? current + 26 : current )); // 26 = number of latin letters
64
67
} else {
65
68
decoded .append (current );
0 commit comments