首先,这是到目前为止的代码
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;
}
(顺便说一下,文本是输入的字符串。而toLower则使字符串全部小写,以便于转换。)
我完成了大部分任务,但其中一部分任务是将输入的每个字母移到5个空格上。 A变成F,B变成G,依此类推。
到目前为止,我还没有将字母转换为数字,但是我很难添加到它,然后又将其返回给字母。
当我运行程序并输入“ abc”之类的输入时,将得到“ 8”。它只是将它们全部加在一起。
任何帮助将不胜感激,如有必要,我可以发布完整的代码。
最佳答案
几个问题-
首先-我相信您不需要第一个eNum = (int) - (int)'a' + 5;
就可以了-(int) -
。您的表达式将始终导致负整数。
而不是返回eNum = (int)c + 5;
,您应该将其转换为character并将其添加到字符串中并在结尾处返回字符串(或者您可以创建一个与string长度相同的字符数组,继续将字符存储在该数组中,然后返回一个字符串从字符数组创建)。
代替在条件中使用eNum
,应该使用a
,它表示c
索引处的当前字符。
我猜不是代码中的所有变量都是该类的成员变量(实例变量),因此您应该在代码中使用数据类型定义它们。
示例代码更改-
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;
关于java - Java-帮助将字母转换为整数,加5,然后转换回字母,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31081509/