99 * @author khalil2535
1010 */
1111public class Caesar {
12- private static char normalizeShift (final int shift ) {
13- return (char ) (shift % 26 );
12+ private static int normalizeShift (final int shift ) {
13+ return ((shift % 26 ) + 26 ) % 26 ;
1414 }
1515
1616 /**
@@ -22,21 +22,18 @@ private static char normalizeShift(final int shift) {
2222 public String encode (String message , int shift ) {
2323 StringBuilder encoded = new StringBuilder ();
2424
25- final char shiftChar = normalizeShift (shift );
25+ final int shiftChar = normalizeShift (shift );
2626
2727 final int length = message .length ();
2828 for (int i = 0 ; i < length ; i ++) {
29- // int current = message.charAt(i); //using char to shift characters because
30- // ascii
31- // is in-order latin alphabet
32- char current = message .charAt (i ); // Java law : char + int = char
29+ final char current = message .charAt (i );
3330
3431 if (isCapitalLatinLetter (current )) {
35- current += shiftChar ;
36- encoded .append ((char ) (current > 'Z' ? current - 26 : current )); // 26 = number of latin letters
32+ final int shifted = current + shiftChar ;
33+ encoded .append ((char ) (shifted > 'Z' ? shifted - 26 : shifted )); // 26 = number of latin letters
3734 } else if (isSmallLatinLetter (current )) {
38- current += shiftChar ;
39- encoded .append ((char ) (current > 'z' ? current - 26 : current )); // 26 = number of latin letters
35+ final int shifted = current + shiftChar ;
36+ encoded .append ((char ) (shifted > 'z' ? shifted - 26 : shifted )); // 26 = number of latin letters
4037 } else {
4138 encoded .append (current );
4239 }
@@ -53,17 +50,17 @@ public String encode(String message, int shift) {
5350 public String decode (String encryptedMessage , int shift ) {
5451 StringBuilder decoded = new StringBuilder ();
5552
56- final char shiftChar = normalizeShift (shift );
53+ final int shiftChar = normalizeShift (shift );
5754
5855 final int length = encryptedMessage .length ();
5956 for (int i = 0 ; i < length ; i ++) {
60- char current = encryptedMessage .charAt (i );
57+ final char current = encryptedMessage .charAt (i );
6158 if (isCapitalLatinLetter (current )) {
62- current -= shiftChar ;
63- decoded .append ((char ) (current < 'A' ? current + 26 : current )); // 26 = number of latin letters
59+ final int shifted = current - shiftChar ;
60+ decoded .append ((char ) (shifted < 'A' ? shifted + 26 : shifted )); // 26 = number of latin letters
6461 } else if (isSmallLatinLetter (current )) {
65- current -= shiftChar ;
66- decoded .append ((char ) (current < 'a' ? current + 26 : current )); // 26 = number of latin letters
62+ final int shifted = current - shiftChar ;
63+ decoded .append ((char ) (shifted < 'a' ? shifted + 26 : shifted )); // 26 = number of latin letters
6764 } else {
6865 decoded .append (current );
6966 }
0 commit comments