99 * @author khalil2535
1010 */
1111public class Caesar {
12+ private static char normalizeShift (final int shift ) {
13+ return (char ) (shift % 26 );
14+ }
1215
1316 /**
1417 * Encrypt text by shifting every Latin char by add number shift for ASCII
@@ -19,7 +22,7 @@ public class Caesar {
1922 public String encode (String message , int shift ) {
2023 StringBuilder encoded = new StringBuilder ();
2124
22- shift %= 26 ;
25+ final char shiftChar = normalizeShift ( shift ) ;
2326
2427 final int length = message .length ();
2528 for (int i = 0 ; i < length ; i ++) {
@@ -29,10 +32,10 @@ public String encode(String message, int shift) {
2932 char current = message .charAt (i ); // Java law : char + int = char
3033
3134 if (isCapitalLatinLetter (current )) {
32- current += shift ;
35+ current += shiftChar ;
3336 encoded .append ((char ) (current > 'Z' ? current - 26 : current )); // 26 = number of latin letters
3437 } else if (isSmallLatinLetter (current )) {
35- current += shift ;
38+ current += shiftChar ;
3639 encoded .append ((char ) (current > 'z' ? current - 26 : current )); // 26 = number of latin letters
3740 } else {
3841 encoded .append (current );
@@ -50,16 +53,16 @@ public String encode(String message, int shift) {
5053 public String decode (String encryptedMessage , int shift ) {
5154 StringBuilder decoded = new StringBuilder ();
5255
53- shift %= 26 ;
56+ final char shiftChar = normalizeShift ( shift ) ;
5457
5558 final int length = encryptedMessage .length ();
5659 for (int i = 0 ; i < length ; i ++) {
5760 char current = encryptedMessage .charAt (i );
5861 if (isCapitalLatinLetter (current )) {
59- current -= shift ;
62+ current -= shiftChar ;
6063 decoded .append ((char ) (current < 'A' ? current + 26 : current )); // 26 = number of latin letters
6164 } else if (isSmallLatinLetter (current )) {
62- current -= shift ;
65+ current -= shiftChar ;
6366 decoded .append ((char ) (current < 'a' ? current + 26 : current )); // 26 = number of latin letters
6467 } else {
6568 decoded .append (current );
0 commit comments