我写了一个简单的密码(不应该很难),通过将字符更改为 char 并将索引添加到 chek 来对值进行加扰,从而对给定的字符串进行加密。问题是,当我破译代码时,它会剪切最后一个字符。现在我确信这是一个简单的菜鸟错误,但我正在努力寻找罪魁祸首。
任何帮助将不胜感激!
public class Cipher {
public void cipher(String strArg) {
String placeholder = strArg;
System.out.println("Unciphered text: "+placeholder);
char[] charArg = placeholder.toCharArray();
char[] cipheredArg;
int lengthArg = charArg.length-1;
cipheredArg = new char[lengthArg];
System.out.print("Ciphered text: ");
for (int i = 0; i < lengthArg; i++) {
char current = charArg[i];
cipheredArg[i] = (char) (current + i);
System.out.print(cipheredArg[i]);
}
System.out.print("\nDeciphered text: ");
for (int i = 0; i < lengthArg; i++) {
char current = cipheredArg[i];
charArg[i] = (char) (current - i);
System.out.print(charArg[i]);
}
}
public static void main(String[] args) {
Cipher show = new Cipher();
show.cipher("The quick brown fox jumps over the lazy dog.");
}
}
输出为:
Unciphered text: The quick brown fox jumps over the lazy dog.
Ciphered text: Tig#uzojs)l}{?|/v??3~????9????>???B????G???
Deciphered text: The quick brown fox jumps over the lazy dog
正如您所看到的,破译的文本中缺少点。有什么想法吗?
最佳答案
您正在对 Java 中从零开始的索引进行双重补偿
这将迭代的长度减少了 1
int lengthArg = charArg.length-1;
这也是由于 < 运算符造成的
for (int i = 0; i < lengthArg; i++) {
规范的修复方法是使用数组的完整长度和 < 运算符
int lengthArg = charArg.length;
// ...
for (int i = 0; i < lengthArg; i++) {
关于java - 无法显示循环中的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30036661/