【问题标题】:Can't display all characters in the loop无法显示循环中的所有字符
【发布时间】: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


【解决方案1】:

您正在对 Java 中从零开始的索引进行双重补偿

这会将迭代的长度减少一

int lengthArg = charArg.length-1;       

因为

for (int i = 0; i < lengthArg; i++) {

规范的解决方法是使用数组的全长和

int lengthArg = charArg.length;       
// ...
for (int i = 0; i < lengthArg; i++) {

【讨论】:

    【解决方案2】:

    你可以这样做:

    for (int i = 0; i < charArg.length; i++)
    

    因为 char 数组的长度应该是 0..n-1,但看起来它是 n 个元素。就像,你有单词“Hello”,数组从元素 0 开始,即“H”到 4,即“o”。看起来它是5个元素。希望对你有帮助。

    【讨论】:

    • 由于cipheredArg = new char[lengthArg]而导致IOOBE崩溃
    • 是的,你说得对,虽然这很明显,但我专注于其他事情。我的错误:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多