【发布时间】:2015-05-04 17:55:07
【问题描述】:
我编写了一个简单的密码(不应该很难),它通过将字符更改为 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
如您所见,破译文本中缺少点。有什么想法吗?
【问题讨论】:
-
int lengthArg = charArg.length-1;为什么是-1? -
这么简单,嗯?非常感谢,我知道这将是显而易见的。出于某种原因,我认为 .length 从 1 开始计数,而不是 0,并且确信这会使我的循环超出范围,但我想我错了。恭喜,我的朋友。
标签: java arrays string loops char