0

在我的程序中,我有一个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方法的语句。我究竟做错了什么?sellItemShop

4

1 回答 1

5

调用后allShops[...].sellItem()allShops仍然是一个有效的数组引用——不可能null!您可能想测试以下的返回sellItem

if(allShops[shopInput-1].sellItem() == null)
于 2013-03-09T07:21:23.517 回答