2013-05-17 43 views
-9

我已經寫了這段代碼,因爲我想打印出7個數字中的5個最低數字,但不想打印重複值。現在它給了一些例外。我的代碼有什麼問題?這是例外

該怎麼辦?

我想我需要一個動態類型的Arraylist,但我不知道應用那個確切的。

class mycode{ 

    public static void main(String[] args) { 

    boolean lowStraightFound = false; 
    int firstCard=0 ; 
    int firstCardIndex = 0; 
    int lastCard =0; 
    int lastCardIndex = 0; 
    int c[]={1,2,3,3,4,5,7}; 
    int[] inarow = new int[20]; 
    int index[]=new int[5]; 
    int last=0; 

    int num = c.length; 
    for (int i = 0; i < num; i++) { 
     int card = c[i]; 
     if (lastCard!= 0) { 
      int lastOrd = lastCard; 
      int cardOrd = card; 
      if (cardOrd - lastOrd == 1) { 
       inarow[0]++; 
       lastCardIndex = i; 
       last++; 
       index[last]=i; 
      } else if (cardOrd - lastOrd != 0) { 
       inarow[0] = 1; 
       firstCard = card; 
       firstCardIndex = i; 
       last=0; 
       index[last]=i; 
       }else if(cardOrd - lastOrd == 0){ 
        index[last]=i; 
        last=i; 
       } 
     } else { 
      firstCard = card; 
      firstCardIndex = i; 
      index[last]=i; 
     } 
     lastCard = card; 

     if (inarow[0] == 5) { 
      lowStraightFound = true; 
      break; 
     }   
    } 
     for (int i = last; i >= 0; i--) { 
      System.out.println(c[i]); 
     } 
     } 
} 
+7

爲什麼不提供它給出的例外? –

+5

刪除代碼中的空行。告訴我們拋出異常的位置。刪除解釋您的問題時不必要的所有其他代碼。 –

+0

當你在調試器中遍歷你的代碼時,你會看到什麼? –

回答

0

我想你會得到一個ArrayIndexOutOfBoundsException

爲了防止這種情況,第28行,改變這種:

index[last]=i; 

成這樣:

index[last++]=i; 

或更改線路14:

int index[]=new int[5]; 

成這樣:

int index[]=new int[6]; 

由於索引上升到5(數組大小-1)