2013-04-24 190 views
1

我想用一個數組來處理一個橋牌手,然後讓它按套裝排序。該計劃處理所有13卡,但後來我得到的錯誤,線程「主」異常java.lang.ArrayIndexOutOfBoundsException:13

"Exception in thread "main" 
java.lang.ArrayIndexOutOfBoundsException: 13 
at DeckStuff.main(DeckStuff.java:29)" 

任何幫助,將不勝感激。

public static void main(String[] args) { 

    Card.shuffleDeck(); 

    Card.dumpCards(); 

    Card[] bridgeHand = new Card[13]; 

    for (int i = 0; i < bridgeHand.length; i++) { 
     bridgeHand[i] = Card.dealCard(); 
    } 

    for (int i = 0; i < bridgeHand.length; i++) { 
     System.out.print(bridgeHand[i]); 
    } 
    System.out.println(); 

    Card.sortHand(bridgeHand); 

    String[] suit = {"Spades", "Hearts", "Diamonds", "Clubs"}; 

    int j = 0; 
    for(int i = 0; i < 4; i++) { 
     String s = suit[i].substring(0,1); 
     System.out.print("\n" + s + ": "); 

     while (bridgeHand[j].getCardSuitName().equals(suit[i])) { 
      System.out.print(bridgeHand[j]); 
      j++; 
     } 
    } 
} 
} 
+1

您應表明其行‘29’在未來,因爲 – 2013-04-24 23:21:19

回答

3

j沒有被複位,while循環就停止,因爲它遇到了錯誤的適合卡,因爲你想要去了所有的人,但只打印正確適用卡這是不正確的。

嘗試:

for(int i = 0; i < 4; i++) { 
    String s = suit[i].substring(0,1); 
    System.out.print("\n" + s + ": "); 

    for(int j = 0; j < bridgeHand.length; j++) { 
     if (bridgeHand[j].getCardSuitName().equals(suit[i])) { 
      System.out.print(bridgeHand[j]); 
     } 
    } 
} 
+0

你可以爲我建立它嗎?當我在for循環中將j重置爲0時,它只處理「黑桃」而沒有其他任何東西。 – user2317612 2013-04-24 23:11:32

+0

@ user2317612 I已經更新了我的答案,請給我一個鏡頭 – 2013-04-24 23:16:40

+0

這很有效,謝謝。我猜我的while循環被打破了。 – user2317612 2013-04-24 23:24:43

2

java.lang.ArrayIndexOutOfBoundsException:13

這意味着你訪問數組越界。你給它的索引值爲13.我甚至還沒有讀你的代碼,但我猜這是一個錯誤的錯誤。

...閱讀...

是的。你不斷增加j。錯誤信息也會給你一個行號。

在DeckStuff.main(DeckStuff.java:29)」

這意味着該錯誤是在第29行中的文件DeckStuff.java

相關問題