2015-05-04 68 views
-1

任何幫助,非常感謝。我一直在爲此撓頭,不知道爲什麼我的ArrayLists都不喜歡.add()任何東西。錯誤發生在名爲SimplePoker的類中,稱爲play。我也雜耍其他兩個類叫甲板和卡在這裏,所以我覺得我的問題有,這樣做,但我目前還不完全肯定:ArrayList錯誤,當涉及.add()

public void play() 
{ 
    //Array lists 
    ArrayList<Card>currentHand = new ArrayList<Card>(); 
    ArrayList<Decks> dealCards = new ArrayList<Decks>(); 

    // implement this method! 
    while(balance >0){ 


     //Showing the balance 
     balance = startingBalance; 
     System.out.println("Your current balance is: " +balance); 

     //Scanner asking for wager 
     Scanner fromKeyboard = new Scanner(System.in); 
     System.out.println("How much would you like to wager? "); 
     bet = fromKeyboard.nextInt(); 

     //To play 
     if(bet <= balance){ 
      Scanner in = new Scanner(System.in); 
      List<Card> discardCards; 
      System.out.println("Lets play!"); 

      //Placing bet 
      balance -= bet; 

      //Distributing first 5 cards 
      for(int i=0; i<5; i++){ 
       currentHand.add(dealCards.get(i)); 
       dealCards.remove(i); 

      } 

      //Discarding cards 
      System.out.println("Which cards would you like to throw (Enter any of the digits: 1 2 3 4 5, respectively: "); 
      while (in.hasNext()){ 
       discardCards.add(in); 
      } 

     } 
     //Or not to play 
     else 
      System.out.println("Not a valid wager"); 

    } 

} 

當我運行它,我得到此錯誤消息:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
The method add(Card) in the type List<Card> is not applicable for the arguments (Decks) 
The method add(Card) in the type List<Card> is not applicable for the arguments (Scanner) 
+1

'類型列表中的方法add(Card)不適用於參數(Scanner)''。它表示您正試圖將'Scanner'實例添加到'List '。 –

+1

'dealCards'包含'Desks','currentHand'包含'Card',您不能將'Desks'添加到'Card'列表中...... – MadProgrammer

+0

看起來您創建的ArrayList是泛型類型'Card '並且你正在添加'Decks'類的對象。如果'Decks'類不是'Card'類的子類,那麼JVM將通過這個預期。如果設計允許的話,可以讓您的ArrayList類型爲'Decks'或擴展'Decks'類爲'Card' –

回答

3

你的數組有不同的類型。

ArrayList<Decks> dealCards = new ArrayList<Decks>(); 
ArrayList<Card>currentHand = new ArrayList<Card>(); 
List<Card> discardCards; 

currentHand.add(dealCards.get(i)); 「在」

while (in.hasNext()){ 
      discardCards.add(in); 
     } 

您不能添加到列表中: - 你不能甲板對象添加到卡陣列

也在於此。您需要從「in」中讀取並將值轉化爲對象。

+0

我想我可以直接做,但我明白,謝謝。首先這真的幫了我很大的忙 – Edrich

1

dealCards.get(i)返回Decks的實例。 所以它不能被添加到currentHand至極預期cards的一個實例。