首先,这是我目前的代码
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'。它只是将它们全部添加起来。
非常感谢任何帮助,如有必要,我可以发布完整的代码。
答案 0 :(得分:1)
几个问题 -
首先 - eNum = (int) - (int)'a' + 5;
您不需要第一个(int) -
我相信,您可以这样做 - eNum = (int)c + 5;
。你的表达式总是会产生一个负整数。
您应该将其转换为字符并将其添加到字符串并在结尾处返回字符串(或者您可以创建与字符串长度相同的字符数组,并保留字符,而不是返回eNum
。在数组中,并返回从字符数组创建的字符串。
不应在条件中使用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;
答案 1 :(得分:0)
//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);
希望这是你正在寻找的。 p>
答案 2 :(得分:0)
尝试这样的事情,我相信这有几个好处:
hns = [['a','b','c'],['c','b','a'],['b','a','c']]
M={}
for x in hns:
for i,y in enumerate(x):
if y in M:
M[y].append(i+1)
else:
M[y]=[i+1]
print M
# {'a': [1, 3, 2], 'c': [3, 1, 3], 'b': [2, 2, 1]}
这段代码有点冗长,但也许随后更容易理解。我介绍了StringBuilder,因为它比执行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();
}