2013-03-09 80 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

相關問題