无法显示循环中的所有字符
Can't display all characters in the loop
我写了一个简单的密码(不应该很难),它通过将字符更改为 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
中对从零开始的索引进行双重补偿
这减少了一个迭代的长度
int lengthArg = charArg.length-1;
因为 < 运算符
for (int i = 0; i < lengthArg; i++) {
规范的解决方法是使用数组的全长和 < 运算符
int lengthArg = charArg.length;
// ...
for (int i = 0; i < lengthArg; i++) {
你可以这样做:
for (int i = 0; i < charArg.length; i++)
因为char数组的长度应该是0..n-1,但看起来是n个元素。比如,你有单词 "Hello" 并且数组以元素 0 开始,即 "H" 到 4 即 "o"。看起来它是 5 个元素。希望对您有所帮助。
我写了一个简单的密码(不应该很难),它通过将字符更改为 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
中对从零开始的索引进行双重补偿这减少了一个迭代的长度
int lengthArg = charArg.length-1;
因为 < 运算符
for (int i = 0; i < lengthArg; i++) {
规范的解决方法是使用数组的全长和 < 运算符
int lengthArg = charArg.length;
// ...
for (int i = 0; i < lengthArg; i++) {
你可以这样做:
for (int i = 0; i < charArg.length; i++)
因为char数组的长度应该是0..n-1,但看起来是n个元素。比如,你有单词 "Hello" 并且数组以元素 0 开始,即 "H" 到 4 即 "o"。看起来它是 5 个元素。希望对您有所帮助。