运行时错误:线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:7

时间:2015-12-07 15:54:06

标签: java

此代码有什么问题?

public String convertBinaryStringToString(String string){
    StringBuilder sb = new StringBuilder();
    char[] chars = string.toCharArray();

    // String TextKey="";
    String plaintext="";

    //for each character
    for (int j = 0; j < chars.length; j+=8) {
        int idx = 0;
        int sum =0;

        //for each bit in reverse
        for (int i = 7; i>= 0; i--) {
            if (chars[i+j] == '1') {
                sum += 1 << idx;
            }
            idx++;
        }
        System.out.println("The ascii for the binary is :"+sum); //debug
        plaintext = (char)sum+"";
        plainstr += plaintext;
        key_arr = StrKey.toCharArray();
        System.out.println("The ascii for chracter for ascii is :"+plainstr); 
    }
    return plainstr;
}

它给了我这个运行时错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 
at dec.convertBinaryStringToString(dec.java:83) 
at dbconnection.updateRows(dbconnection.java:122) 
at mainenc.main(mainenc.java:8) 

第83行是if (chars[i+j] == '1')

1 个答案:

答案 0 :(得分:0)

请注意,您将超过8个字节的块,并且对于每个块,您尝试遍历块中的每个字符。处理最后一个块时会出现问题,因为它可能少于8个字符。重写这一行:

if (chars[i+j] == '1') {

if (i + j < chars.length && chars[i+j] == '1') {