Java-帮助将字母转换为整数,加5,然后再转换回字母



首先,这是我迄今为止的代码

    public int encrypt() {
/* This method will apply a simple encrypted algorithm to the text.
 * Replace each character with the character that is five steps away from
 * it in the alphabet. For instance, 'A' becomes 'F', 'Y' becomes '~' and
 * so on. Builds a string with these new encrypted values and returns it.
 */
    text = toLower;
    encrypt = "";
    int eNum = 0;
    for (int i = 0; i <text.length(); i++) {
        c = text.charAt(i);
        if ((Character.isLetter(c))) {
       eNum = (int) - (int)'a' + 5;
        }  
    }

    return eNum;    
}

(顺便说一下,text是输入的字符串。toLower使字符串的大小写都变小,以便于转换。)

我完成了大部分作业,但其中一部分任务是将输入的每个字母移动5个空格。A变为F,B变为G等。

到目前为止,我还没有将字母转换为数字,但我很难将其添加到数字中,然后再将其返回为字母。

当我运行程序并输入诸如"abc"之类的输入时,我得到"8"。它只是把它们加在一起。

任何帮助都将不胜感激,如果需要,我可以发布完整的代码。

少数问题-

  1. 首先-eNum = (int) - (int)'a' + 5;你不需要第一个(int) -,我相信你可以做-eNum = (int)c + 5;。您的表达式总是会产生一个负整数。

  2. 您不应该返回eNum,而应该将其转换为字符并添加到字符串中,然后在末尾返回字符串(或者您可以创建一个与字符串长度相同的字符数组,继续将字符存储在数组中,然后返回从字符数组创建的字符串)。

  3. 不应在条件中使用a,而应使用c,它表示ith索引处的当前字符。

  4. 我猜并不是代码中的所有变量都是类的成员变量(实例变量),所以应该在代码中使用数据类型来定义它们。

代码更改示例-

String text = toLower; //if toLower is not correct, use a correct variable to get the data to encrypt from.
        String encrypt = "";
    for (int i = 0; i <text.length(); i++) {
        char c = text.charAt(i);
        if ((Character.isLetter(c))) {
       encrypt += (char)((int)c + 5);
        }  
    }

   return encrypt;
//Just a quick conversion for testing
String yourInput = "AbC".toLowerCase();
String convertedString = "";
for (int i = 0; i <text.length(); i++) {
    char c = yourInput.charAt(i);
    int num = Character.getNumericValue(c);
    num = (num + 5)%128 //If you somehow manage to pass 127, to prevent errors, start at 0 again using modulus
    convertedString += Integer.toString(num);
}
System.out.println(convertedString);

希望这就是你想要的。

试试这样的东西,我相信它有几个优点:

public String encrypt(String in) {
    String workingCopy = in.toLowerCase();
    StringBuilder out = new StringBuilder();
    for (int i = 0; i < workingCopy.length(); i++) {
        char c = workingCopy.charAt(i);
        if ((Character.isLetter(c))) {
            out.append((char)(c + 5));
        }
    }
    return out.toString();
}

这段代码有点冗长,但也许这样会更容易理解。我介绍StringBuilder是因为它比string = string + x 更高效

相关内容

最新更新