0

我在“商店”类中有以下代码:

public Item sellItem()
{
    displayItems();
    int indexID = Shop.getInput();
    if (indexID <= -1 && indexID >= wares.length)
    {
        System.out.println("Null"); // For testing purposes
        return null;
    }
    else
    {
        return wares[indexID];
    }
}

而且我想知道如何编写一个if语句来检查此方法是否正在null为我while的主类中的循环返回:

int shopInput = scan.nextInt();
if(shopInput >= 1 && shopInput <= allShops.length)
{
   boolean leaveShop = true;
   while(leaveShop)
   {
      allShops[shopInput - 1].sellItem();
      if(???????? == null);
      {
         System.out.println("still null"); // For testing purposes
         leaveShop = false;
      }
   }
}
4

2 回答 2

0
Item item = allShops[shopInput - 1].sellItem();
if (item == null) {
    System.out.println("still null"); // For testing purposes
    ...
}

(请注意,我;从行尾删除了if

于 2013-03-09T05:58:43.133 回答
0

使用它来检查空值。

if (allShops[shopInput - 1].sellItem() == null) {}

编辑:删除不必要的双重否定

于 2013-03-09T05:59:35.037 回答