无法显示循环中的所有字符

时间:2015-05-04 17:55:07

标签: java arrays string loops char

我写了一个简单的密码(不应该很难)通过将字符更改为char并将索引添加到chek来加密给定字符串来加密值。问题是,当我破译代码时,它会删除最后一个字符。现在我确定这是一个简单的新手错误,但我很难找到罪魁祸首。

非常感谢任何帮助!

RewriteEngine on
RewriteRule ^account$ account.php
RewriteRule ^home$ myhome.php
RewriteRule ^options$ options.php
RewriteRule ^login$ login.php
RewriteRule ^links$ editlinks.php
RewriteRule ^help$ howto.php
RewriteRule ^$ index.php
RewriteRule ^forgot$ forgot.php
RewriteRule ^r$ redirect.php
RewriteRule ^r/(.*)$ redirect.php?id=$1
RewriteCond %{REQUEST_URI} !(login.php|login)
RewriteRule (.*) external.php?parameter=$1 [L]

输出结果为:

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.");
    }
}

正如您所看到的,在解密文本中缺少点。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您正在对Java中基于零的索引进行双重补偿

这减少了迭代一次的长度

int lengthArg = charArg.length-1;       

由于&lt;操作

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

规范修复将使用数组的全长和&lt;操作

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

答案 1 :(得分:-1)

你可以这样做:

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

Becouse char数组的长度应为0..n-1,但看起来是n个元素。就像,你有字#&#34;你好&#34;并且数组以元素0开始,即&#34; H&#34;到4是&#34; o&#34;。看看它的5个要素。我希望它可以帮助你。