繁体   English   中英

数组索引超出范围认为存在特定线

[英]Array Index out of bounds think there is a specfic line

线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:ham.main(ham.java:34)为100

我的控制台上的第34行说是否(h [c] == 1)

我写了一个代码来生成汉明码。.我正在收到javaindexoutbounds异常。.我什至给了大得不可思议的数组大小以阻止它..仍然无法正常工作! 即使您有足够的空间来放置阵列,阵列也会出站

第27行可能是一个错误...正在检查c

 import java.util.*;

public class ham {
public static void main(String ar[]) {
    Scanner s = new Scanner(System.in);
    System.out.println("input no. of bits");
    int n = s.nextInt();
    int a[] = new int[100]; // user's input
    int h[] = new int[100]; // hamming code array
    System.out.println("i/p the data");
    int i = 1, j = 1, pb = 1;
    for (i = 1; i < n + 1; i++)
        a[i] = s.nextInt();
    i = 1;

    while (i < n + 1) {
        if (j == pb) // if the index is a parity bit leave it
        {
            j++;
            pb = pb * 2;
        } else {
            h[j] = a[i];
            j++;
            i++;
        } // else copy the data bits from a[] to h[]
    }

    int c = 0, counter = 0; // to fill the parity bits(k)
    for (int k = 1; k <= j; k = 2 * k) {
        c = k;
        while (c <= j) // 'j' is position of the last data bit in h[]
        {
            for (c = k; c < (c + k); c++) {
                if (h[c] == 1)   // this is line 34
                    counter++;
            }
            c = c + k + 1;
        }
        if (counter % 2 == 0)
            h[k] = 0;
        else
            h[k] = 1;
    }
    System.out.println("hamming code is");
    for (i = 1; i <= j; i++)
        System.out.print(h[i] + " ");
}

}

if (h[c] == 1)测试引起异常。

您的h数组的固定大小为100 ,但是c的最大值似乎取决于用户的输入n 您将需要弄清楚如何根据用户输入动态确定阵列大小。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM