繁体   English   中英

为什么Java方法返回null?

[英]Why does Java method return null?

我正在尝试调试为什么我的Java方法返回null。 这是详细信息。

我们正在制作一个简单的卡片“游戏”,而Im在调用外部方法和创建新对象时遇到了麻烦。这是一副纸牌..因此,一类为纸牌,一类为纸牌,一类为游戏

这是我的课程代码

 public class Game
 {
  private InputReader reader;
  private Deck deck;
  private ArrayList<Card> listCard;

/**
 * Constructor for objects of class Game
 */
public Game()
{
    deck = new Deck();
    reader = new InputReader()
    listCard = new ArrayList<Card>();
}

/**
 *
 */
public void dealCard()
{
   listCard.add(deck.takeCard());
}

}// End of Game class

这是甲板类,我将从中获取方法

 import java.util.ArrayList;
 /**
  * Write a description of class Deck here.
  * 
  * @author  
  * @version 2012.05.31
  */
 public class Deck
{
private ArrayList<Card> redblue;

/**
 * Main constructor for objects of class Deck
 */
public Deck()
{
    redblue = new ArrayList<Card>();
}


   public Card takeCard()
{
      **return redblue.remove(0);**  /// this is the Index.pointer.exception
}



}
}// End of class

所以我的问题是我试图将第一张卡从卡组中取出并添加到我的“手”中。所以我试图调用DealCard(),后者调用takeCard().. takeCard()正常,但是当我尝试调用是否通过DealCard()返回null和错误,因为我无法将null添加到arrayList ..我认为我的问题可能是外部方法调用,而没有使用正确的变量来增强,我不知道

提前致谢

***编辑。 删除了不相关的方法和类。

查看Deck的构造函数:

public Deck()
{
    redblue = new ArrayList<Card>();
}

在构造函数运行之后,redBlue ArrayList中有多少张卡?

如果您尝试从该ArrayList中移除卡,您认为会发生什么?

我认为您需要从主游戏类中发布更多代码,向我们展示甲板和纸牌类的用法。 现在唯一引起我注意的是:

public Card takeCard()
{
      **return redblue.remove(0);**  /// this is the Index.pointer.exception
}

据此,在以下情况下会引发异常:

IndexOutOfBoundsException - if index out of range (index < 0 || index >= size()).

您确定您的甲板上装满卡了吗? 您可以在方法中添加检查。 如果您的卡片列表为空,则0 =它的大小。

public void dealCard()
{
   Card card = deal.takeCard();

   if (card != null)
      listCard.add(deck.takeCard());
}

public Card takeCard()
{
    if ( !this.redblue.isEmpty() )
        return redblue.remove(0);

    return null;        
} 

不知何故,您的第一个元素

redblue

一片空白。 在ArrayList中允许为空。

我的猜测是,有更多的代码可以在卡片组中填充,并且第一次将null添加到ArrayList

此处检查ArrayList规范。

在我看来,redblue实际上没有任何东西! 当您像这样初始化它时:

redblue = new ArrayList<Card>();

您只是为Cards创建一个空容器,而不是将Cards实际放入其中。 您可能想要做的是创建一个函数来为redblue ..之类的东西生成卡。

public ArrayList<Card> createInitialDeck(){ 
  //Create an empty ArrayList
  //Do some code here to create new cards..
       //you might want to consider nested for loops if you're creating 13 cards of 4 different suits for example
       //while inside those for loop add each new card object to your array list

   //return arrayList;
}

然后代替redblue = new ArrayList<Card>(); 你会做redblue = createInitialDeck();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM