Hey guys, I am making something that it takes a char, then it sums it with 5 and returns the new char according to the ASCII table, for example input is 'a' , then output will be 'f'. This code is doing it somewhat ..

public static String Puzzle(String s) {
        char[] c = new char[s.length()];
        for(int i =0; i<s.length();i++)
        c[i] =(char) (s.charAt(i) + 5);
        return new String(c);

but the problem is that if I get 'z' input for example, my result is not what it has to be since the program should return back from 'a' and forward till count 5 and return the new char. Any ideas how to work around this and keep it so that it loops back the the chars 97-122 (small letters in english)

3 Years
Discussion Span
Last Post by Slavi

97 to 121 %122 gives it right but then when I go at 122 or higher than it gets scrumbled


Assume a to be 0, z 25. That would be your index. You can then add 97 to get the character you need. In pseudo:

index = char - 97
newIndex = (index + 5) % 26
newChar = 97 + newIndex

It worked thanks, just out of curiousity, would it be able to work if we don't substract 97?


No. The modulus operator is zero based. It will return a value between 0 and the one you specify (exclusive). So if you do % 122 it will return a value between 0 and 121. Consider 97 your base, and 0 to 25 the index of the number you want.


One small point: instead of using the mysterious 97, you can use the char literal 'a' which makes the code far more obvious, eg

    index = char - 'a'
    newIndex = (index + 5) % 26
    newChar = 'a' + newIndex
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.