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

标签 java arrays string loops char

我写了一个简单的密码(不应该很难),通过将字符更改为 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/

相关文章:

java - Linux\BSD 网络编程

Java 泛型 : Subclassing a generic superclass - is subclass a reifiable type?

Java Enum.valueOf() 问题

javascript - React JS - 如何将不同的 Prop 传递到其他 Prop 的映射中

c - C 中指针的二分查找

javascript - 检索一个数组中所有输入的值 - Jquery

c - 反转名字 - 在名字字母后打印垃圾

java - 在Java中,如何在所有实例中将字符串中多个位置出现的符号替换为另一个符号?

javascript - 比较 2 字符串给出 false 结果,即使它们相同

带 GUI 的 Java 内存游戏 - 字符串和数组比较