0

私のプログラムには、whileショップのリストを表示し、ショップ ID に対応する入力を求めるループがあります。ユーザーがクラスで作成されたショップの配列の外に整数を入力するShopと、ループを終了して続行します。このループ内には、以下のクラスのメソッドwhileを呼び出す別のループがあります。sellItemShop

  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のメソッドのステートメントを正しく呼び出していることを確認するために「まだnull」を出力することはできません。私は何を間違っていますか?sellItemShop

4

1 に答える 1

5

を呼び出した後でもallShops[...].sellItem()allShopsは有効な配列参照です-それができる方法はありませんnull!あなたはおそらくからの戻り値sellItemをテストしたいと思うでしょう:

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