[英]Java - Help converting letter to integer, adding 5, then converting back to letter
首先,这是到目前为止的代码
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;
。 您的表达式将始终导致负整数。
而不是返回eNum
您应该将其转换为character并将其添加到字符串中并在末尾返回该字符串(或者您可以创建一个与string长度相同的字符数组,继续将字符存储在该数组中,并返回从字符数组)。
而不是在条件中使用a
,而应使用c
,它在ith
索引处表示当前字符。
我猜不是代码中的所有变量都是该类的成员变量(实例变量),因此您应该在代码中使用数据类型定义它们。
示例代码更改-
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
更有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.