我正在編寫一個程序來計算漢明碼,並且我收到一個數組越界異常。這個問題似乎是用這種方法:無法解決java.lang.ArrayIndexOutOfBoundsException
static int[] computeParityBits(int[] inWord, int[] parityBits) {
for (int i=0, m=2; m < inWord.length; i++) {
m = (int) Math.pow(m, i);
parityBits[i] = processPower(m, inWord);
}
return parityBits;
整數m不改變其使用就可以了Math.pow
功能時的價值。我嘗試了不同的東西,但我似乎無法使其正常工作。只要它們的值低於int[] inWord.length
,該方法應該通過2的所有權力。在此之後,它應該分配parityBits[i]
由方法processPower()
返回的值。
異常收到:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at hamming_code.HammingCoder.computeParityBits(HammingCoder.java:34) at hamming_code.HammingCoder.computeHammingCode(HammingCoder.java:27) at hamming_code.HammingCoder.main(HammingCoder.java:61)
代碼的較大部分:
static int[] computeHammingCode(int[] inWord, int codeLength) {
int[] parityBits = new int[codeLength - inWord.length];
parityBits = computeParityBits(inWord, parityBits);
return parityBits;
}
static int[] computeParityBits(int[] inWord, int[] parityBits) {
for (int i=0, m=2; m < inWord.length; i++) {
m = (int) Math.pow(m, i);
parityBits[i] = processPower(m, inWord);
}
return parityBits;
}
static int processPower(int m, int[] inWord) {
int counter = 0;
for (int i = 0; i < inWord.length; i++){
for (int n = 0; n < m; n++) {
counter = counter + inWord[i];
}
for (int k = 0; k < m; k++) {
i++;
}
}
if (counter % 2 == 0) {
return 0;
} else
return 1;
}
當i = 5時,m小於inWord,但parityBits數組只有4個項。這是拋出異常。 – zgc7009