Nish Grewal Nish Grewal - 4 months ago 10
Java Question

Define a method named encode that accepts a String as input and returns a new String which is the original String encoded using the ROT13 cipher

For example: String "abc" should return "nop".

I did a System.out.println and it is printing the correct result, however, the JUnit Test case is giving me a red bar. The method move13 just takes the character and moves it 13 spaces left or right.

The method encode is where I am having trouble with.

package code;

public class Encoder {

public char move13(char letter) {
if (letter >= 'a' && letter <= 'm') {
return (char)(letter + 13);
}
if (letter >= 'A' && letter <= 'M') {
return (char)(letter + 13);
}
if (letter >= 'n' && letter <= 'z') {
return (char)(letter - 13);
}
if (letter >= 'N' && letter <= 'Z') {
return (char)(letter - 13);
}
return letter;
}

public String encode(String text) {
String valueOfchar = "";
for (int i = 0; i < text.length(); i++) {
char character = text.charAt(i);
character = move13(character);
valueOfchar = String.valueOf(character);
System.out.println(valueOfchar);

}
return valueOfchar;

}
}

Answer

Here you go, hope it helps

public static char move13(char letter) {
    if (letter >= 'a' && letter <= 'm')
        return (char) (letter + 13);
    if (letter >= 'A' && letter <= 'M')
        return (char) (letter + 13);
    if (letter >= 'n' && letter <= 'z')
        return (char) (letter - 13);
    if (letter >= 'N' && letter <= 'Z')
        return (char) (letter - 13);
    return letter;
}

public static String encode(String text) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < text.length(); i++) {
        char character = text.charAt(i);
        character = move13(character);
        sb.append(character);
        //System.out.println(valueOfchar);

    }
    return sb.toString();

}

The char are concatenated in a StringBuilder (sb.append(char)). After each letter processed in move13(), you return the concatenated chars (sb.toString()).