簡體   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