首页 > 解决方案 > 在Java中将数字存储到字符串数组的问题

问题描述

我正在尝试将异或运算的结果存储到字符串数组中。当我如图所示运行我的代码时,它能够打印出这些值。

int[] randnumbs = new int[0];
randnumbs = streamGen(plaintext.length());
String plaintextnumb;

String encryption;

int[] answer = new int[0];
int count = 0;

while(true) {
    plaintextnumb = plaintext.substring(count, count + 2);
    int numbfromfile = Integer.valueOf(plaintextnumb, 16);
    int xored = numbfromfile ^ randnumbs[count];

    encryption = Integer.toHexString(xored);

    System.out.print(encryption + " "); 
    if(count == (plaintext.length() / 2) - 1) {
        break;
    }else {
        count++;
    }
}

结果:

af a0 52 b1 fb 0 a6 75 

当我将变量“加密”更改为字符串数组时,我的代码能够运行,但是当它到达“加密 [count] = Integer.toHexString(xored);”时,接缝停止运行 我以前从未遇到过这个问题。当我运行我的程序时没有出现任何错误,它只是显示一个空的控制台。我还在这行代码之前和之后插入了打印输出语句,并且只能在代码行之前看到打印输出,而不是之后。任何解释为什么会发生这种情况将不胜感激!

int[] randnumbs = new int[0];
randnumbs = streamGen(plaintext.length());
String plaintextnumb;

String[] encryption = new String[0];

int[] answer = new int[0];
int count = 0;

while(true) {
    plaintextnumb = plaintext.substring(count, count + 2);
    int numbfromfile = Integer.valueOf(plaintextnumb, 16);
    int xored = numbfromfile ^ randnumbs[count];

    encryption[count] = Integer.toHexString(xored);

    System.out.print(encryption[count] + " "); 
    if(count == (plaintext.length() / 2) - 1) {
        break;
    }else {
        count++;
    }
}

标签: javaarraysstring

解决方案


问题是数组的大小encryption0因为String[] encryption = new String[0];声明。因此,使用语句赋值,encryption[count] = Integer.toHexString(xored);可能会导致ArrayIndexOutOfBoundsException因为 的值count可能已经增加(可能已经超过0)。

一个解决方案是用所需的大小声明你的数组,例如String[] encryption = new String[10];

另外,请检查您是否在该行放置了一个调试点,encryption[count] = Integer.toHexString(xored);以及您是否在调试模式下运行程序。如果是,这可能是您的程序没有超出这条线的原因。


推荐阅读