2013-03-09 50 views
0

在我的程序中,我有一个while循环,它将显示商店列表并要求输入一个与商店ID相对应的输入。如果用户在商店阵列外输入一个整数,用Shop类创建,它将退出循环并继续。在这个循环中是另一个while环这就要求我下面Shop类的sellItem方法:如何检查类的方法返回是否等于null?

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的声明Shop。我究竟做错了什么?

+0

可否请您编辑的问题只包括相关部分。 – 2013-03-09 08:03:19

回答

5

致电allShops[...].sellItem()后,allShops仍然是一个有效的数组引用 - 有没有办法可以是null!你可能想从sellItem测试返回值

if(allShops[shopInput-1].sellItem() == null) 
+0

哦,甜蜜的耶稣就是这样...... 几小时的头发撕裂,我已经写了一行前的正确答案...谢谢! – 2013-03-09 07:23:20

相关问题