在Java中将数字存储到字符串数组的问题

我正在尝试将xor操作的结果存储到字符串数组中。如图所示运行代码时,它可以打印出值。

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 

当我将变量“ encryption”更改为String数组时,我的代码可以运行,但是当到达“ encryption [count] = Integer.toHexString(xored);”位置时,接缝将停止运行。我以前从未遇到过这个问题。当我运行程序时,没有错误显示,它只是显示一个空控制台。我还在此代码行之前和之后插入了printout语句,并且只能在代码行之前而不是之后看到打印输出。对此原因的任何解释将不胜感激!

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,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++;
    }
}
ww1610 回答:在Java中将数字存储到字符串数组的问题

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

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

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

,

我想是因为您正在创建大小为0的加密数组,所以它不能有值。因此,当您尝试使用加密[计数]时,该值不存在。 使用ArrayList并使用add()方法将字符串添加到列表中

本文链接:https://www.f2er.com/3127970.html

大家都在问