2015-05-04 47 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的一个实例。