如何检查类的返回方法是否等于null?

时间:2013-03-09 07:18:13

标签: java

在我的程序中,我有一个while循环,它将显示商店列表并要求输入,这与商店ID相对应。如果用户在使用Shop类创建的商店数组之外输入一个整数,它将退出循环并继续。在此循环内部是另一个while循环,它调用下面sellItem类的Shop方法:

  public Item sellItem()
  {
     displayItems();
     int indexID = Shop.getInput();
        if (indexID <= -1 || indexID >= wares.length)
        {
            System.out.println("Null"); // Testing purposes
            return null;
        }
        else
        {
            return wares[indexID];
        }
  }
  private void displayItems()
  {
        System.out.println("Name\t\t\t\tWeight\t\t\t\tPrice");
        System.out.println("0. Return to Shops");
     for(int i = 0; i < wares.length; i++)
     {
        System.out.print(i + 1 + ". ");
        System.out.println(wares[i].getName() + "\t\t\t\t" + wares[i].getWeight() + "\t\t\t\t" + wares[i].getPrice());
     }
  }
  private static int getInput()
  {
     Scanner scanInput = new Scanner(System.in);
     int itemID = scanInput.nextInt();
     int indexID = itemID - 1;
     return indexID;
  }

我的主类方法中的while循环如下:

     boolean exitAllShops = true;
     while(exitAllShops)
     {
        System.out.println("Where would you like to go?\nEnter the number which corresponds with the shop.\n1. Pete's Produce\n2. Moore's Meats\n3. Howards Hunting\n4. Foster's Farming\n5. Leighton's Liquor\n6. Carter's Clothing\n7. Hill's Household Products\n8. Lewis' Livery, Animals, and Wagon supplies\n9. Dr. Miller's Medicine\n10. Leave Shops (YOU WILL NOT BE ABLE TO RETURN)");
        int shopInput = scan.nextInt();
        if(shopInput >= 1 && shopInput <= allShops.length)
        {
           boolean leaveShop = true;
           while(leaveShop)
           {
              allShops[shopInput - 1].sellItem();
              if(allShops == null)
              {
                 System.out.println("still null"); // Testing purposes
                 leaveShop = false;
              }
           }
        }
        else
        {
           System.out.println("Are you sure you want to leave?\n1. Yes\n2. No");
           int confirm = scan.nextInt();
           if(confirm == 1)
           {
              exitAllShops = false;
           }
        }

问题在于:

       boolean leaveShop = true;
       while(leaveShop)
       {
          allShops[shopInput - 1].sellItem();
          if(allShops == null)
          {
             System.out.println("still null"); // Testing purposes
             leaveShop = false;
          }
       }

无论我做什么,我都无法打印“仍为空”以确认我正在调用类return的方法sellItem的{​​{1}}语句}。我做错了什么?

1 个答案:

答案 0 :(得分:5)

调用allShops[...].sellItem()后,allShops仍然是有效的数组引用 - 它不可能是null!您可能想要从sellItem

测试返回值
if(allShops[shopInput-1].sellItem() == null)