0

(已编辑)

我的问题陈述:编写一个方法,通过向字符串中的每个字符添加 13 个字母来对传递给该方法的字符串进行编码。如果添加 13 后的字母超过“z”,则“环绕”字母表。然后返回编码的字符串。

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

这就是我到目前为止所拥有的:

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;
}

现在我知道我必须创建一个计数器,以便该方法将继续循环,直到它达到传递的字符串的长度......我知道如果 charAt(index) 小于我的字符 'n'加 13,如果更大,则减去 13。当我把它们放在一起时,虽然我很困惑,只是得到一堆编译错误,比如Type mismatch: cannot convert from int to String.

请注意简单的解释/答案将不胜感激...

* * *所以现在我的问题是它一直告诉我我的输出变量可能没有被初始化

4

2 回答 2

0

此代码不是最高性能的,但适用于 Upper 和 Lower 字符。

你好 → uRyYb

馅饼→ cVr

书→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;
}
于 2014-01-23T15:41:31.157 回答
0

您必须将output变量初始化为空字符串。此外,您总是用output刚刚编码的最后一个字符替换变量的内容。因此,您必须将每个字符添加到outputwith+=而不是=.

所以这里是固定的解决方案:

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;
}

我稍微美化了你的代码,所以每个人都可以看到它的真正作用。

使用 IDE!

于 2014-01-23T15:34:13.980 回答