-5
此代碼中的問題是什麼?運行時錯誤:線程「main」中的異常java.lang.ArrayIndexOutOfBoundsException:7
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')
這意味着你試圖訪問不存在的索引。如果字符串少於'i + j'字符怎麼辦? – Arc676
你的意思是我必須把其他的說法? –
可能的重複[什麼導致java.lang.ArrayIndexOutOfBoundsException,我該如何防止它?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how- do-i-prevent-it) – Tom