簡體   English   中英

數組索引超出范圍異常無緣無故

[英]array index out of bounds exception for no reason

我在編的最后一行獲取數組索引超出范圍的異常, output[1][1]在那里生成了這樣的異常。 但是在上一個循環中,同樣的事情仍然很正常。

{  
    int ict=66,total_slots=12,h1=15,index_count=65;
    String output[][] = new String[ict][total_slots+1];

    for (int x = 0; x < (ict); x++)
        output[x][0] = Integer.toString(x);
    for (int y = 0; y < (total_slots + 1); y++)
        output[0][y] = Integer.toString(y);
    for (int x = 1; x <= (index_count); x++ )
        for (int y = 1; y <= (total_slots); y++)
            output[x][y] = "n";

    for (int x=1; x <= h1; x++) {
        output[x][1]="y";//exception occurs here
        limit[x]++;
    }
}

請記住,當您聲明一個類似於String output[][]=new String[5][5];的數組時String output[][]=new String[5][5]; 然后output[4][4]是您可以訪問的最后一個元素,因為數組索引從0開始

您已將數組聲明為:

String output[][] = new String[ict][total_slots+1];

在您的for循環中

for( int x=1; x<=(ict); x++ )
    for( int y=1; y<=(total_slots); y++)
         output[x][y]="n";

在外循環的最后一次迭代和內循環的第一次迭代中,您正在嘗試訪問output[ict][0] ,這是引發異常的原因。 請記住,由於0是第一個索引,因此ict - 1將是第一個維度的最后一個有效索引。

嘗試這個:

String output[][] = new String[ict][total_slots]; //this is cleaner

for( int x=0; x<ict; x++ )
    for( int y=0; y<total_slots; y++)
         output[x][y]="n";

這樣,外循環的最后一次迭代只會增加到ict - 1

編輯:看來您已經對問題進行了重大編輯。 請不要在以后針對答案回答您的問題,因為這只會使新讀者感到困惑。

正如您的代碼現在一樣,唯一的錯誤(編譯時間不少於,與異常無關)是limit[x]++; 無效,因為尚未在此范圍內聲明limit 否則,該代碼是合法的並且可以正常運行。

    {  
        int ict=66,total_slots=12,h1=15,index_count=65;
..................................................
..................................................
        for (int x=1; x <= h1; x++) {
                output[x][1]="y";//exception occurs here
                limit[x]++;
            }
        }

在最后一個for循環中,您收到ArryIndexOutOfBoundsException,同時嘗試訪問元素output [13] [1]會導致您的數組寬度僅為13,即最大索引將為12,但不大於該值

使用total_slots代替h1

我在編的最后一行獲取數組索引超出范圍的異常,output [1] [1]在那里生成了這樣的異常。

重新檢查控制台輸出。 您必須弄錯了錯誤代碼行,因為無法生成此類異常。 問題很可能在於limit[] ,我們不知道它是如何聲明的。

順便說一句,最后一行是limit[x]++ ;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM