encode string passed to method & add 13

1k Views Asked by At

(EDITED)

My problem statement: write a method that will encode the String passed to the method by adding 13 letters to each character in the String. If the letter after adding 13 exceeds 'z' then "wrap around" the alphabet. Then return the encoded String.

encodeString("hello") → "uryyb"
encodeString("pie") → "cvr"
encodeString("book") → "obbx"

this is what I have so far :

public static String encodeString (String input) {

    String output;

    for (int i = 0; i < input.length(); i++) {
        char c = input.charAt(i);

        if (c >= 'a' && c <= 'm') 
            c += 13;
        else if (c >= 'n' && c <= 'z') 
            c -= 13;

        output= (" " + (c));
    }

    return output;
}

now I know that I have to create a counter so that the method will continue to loop until it reaches the length of the string passed...and I know that if the charAt(index) is less than the character 'n' that I add 13 and if it is greater then I subtract 13. when I put it all together though I just get so confused and just get a bunch of compiling errors like Type mismatch: cannot convert from int to String.

note straightforward explanations/answers would be much appreciated...

***so now my problem is that it keeps telling me my output variable may not have been initialized

2

There are 2 best solutions below

0
On

You have to initialize your output variable as an empty String. Furthermore you are always replacing the contents of the output variable with the last char you've just encoded. So you have to add every char to the output with += instead of =.

So here is the fixed solution:

public static String encodeString(String input) {
    String output = "";       // initialize as empty String

    for (int i = 0; i < input.length(); i++) {
        char c = input.charAt(i);

        if (c >= 'a' && c <= 'm') {
            c += 13;
        } else if (c >= 'n' && c <= 'z') {
            c -= 13;
        }

        output += " " + c;     // add all chars to the String instead of replacing the whole String with "="!
    }

    return output;
}

I beautified your code a bit, so everybody can see what it really does.

Use an IDE!

0
On

This code is not the most performatic but works good with Upper and Lower characters.

hElLo → uRyYb

pIe → cVr

bOoK → oBbX

private static String encodeString(String string) {
    char[] ret = new char[string.length()];

    for (int i = 0; i < string.length(); i++) {
        ret[i] = rot13(string.charAt(i));
    }

    return String.valueOf(ret);
}

public static char rot13(char c) {
    if (Character.isLetter(c)) {
        if (Character.compare(Character.toLowerCase(c), 'a') >= 0
                && Character.compare(Character.toLowerCase(c), 'm') <= 0)
            return c += 13;
        else
            return c -= 13;
    }

    return c;
}