将集合添加到hashmap

时间:2017-07-12 02:54:04

标签: java collections hashmap

尝试完成VendItem&的方法。 Restock ..我不太明白我是怎么想把参数中给出的项目添加到HashMap中的。有人可以解释一下如何完成这个吗?



import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.Scanner;

public class Solution {

   /**
    * The top portion of this class is the main driver and interface, and
    * other classes needed to setup the coding challenge.
    *
    * Located at the end of this file is the VendingMachineImpl class.
    * Please code your solution in the VendingMachineImpl class (stubbed out below).
    */
   public static void main(String args[]) throws Exception {
      // please do not alter this method.
      Collection<VendingMachine.Product> products = null;
      Collection<VendingMachine.Coin> coins = null;
      String itemName = null;
      Collection<VendingMachine.Coin> tender = null;
      Solution.VendingMachine.VendResult result = null;

      Scanner input = new Scanner(System.in);
      String line = input.nextLine();
      if (line != null && !"".equals(line.trim())) {
         Scanner productLine = new Scanner(line);
         products = new ArrayList<VendingMachine.Product>();
         while (productLine.hasNext()) {
            String name = productLine.next();
            Integer price = productLine.nextInt();
            products.add(new VendingMachine.Product(name, price));
         }
      }

      line = input.nextLine();
      if (line != null && !"".equals(line.trim())) {
         Scanner coinLine = new Scanner(line);
         coins = new ArrayList<VendingMachine.Coin>();
         while (coinLine.hasNext()) {
            String coinName = coinLine.next();
            VendingMachine.Coin c = VendingMachine.Coin.valueOf(coinName);
            if (c != null) {
               coins.add(c);
            }
         }
      }

      line = input.nextLine();
      if (line != null && !"".equals(line.trim())) {
         Scanner vendLine = new Scanner(line);
         tender = new ArrayList<VendingMachine.Coin>();
         if (vendLine.hasNext()) {
            itemName = vendLine.next();
            while (vendLine.hasNext()) {
               VendingMachine.Coin c = VendingMachine.Coin.valueOf(vendLine.next());
               if (c != null) {
                  tender.add(c);
               }
            }
         }
      }

      VendingMachine vm = new VendingMachineImpl();
      vm.restock(products, coins);

      if (itemName != null) {
         result = vm.vendItem(itemName, tender);
      }

      System.out.print(getTotalItemCount(vm.getItemCount()));
      System.out.print(" ");
      System.out.print(getCoinAmount(vm.getCoinCount()));

      if (result != null) {
         System.out.print(" ");
         System.out.print(getCoinAmount(result.getChange()));
      }
   }

   // please do not alter this method.
   private static int getTotalItemCount(Map<String, Integer> products) {
      int totalCount = 0;
      if (products != null) {
         for (Integer count : products.values()) {
            if (count != null && count.intValue() > 0) {
               totalCount += count.intValue();
            }
         }
      }
      return totalCount;
   }

   // please do not alter this method.
   private static int getCoinAmount(Collection<Solution.VendingMachine.Coin> coins) {
      int totalAmount = 0;
      for (Solution.VendingMachine.Coin coin : coins) {
         totalAmount += coin.getValue();
      }
      return totalAmount;
   }

   // please do not alter this method.
   private static int getCoinAmount(Map<Solution.VendingMachine.Coin, Integer> coins) {
      int totalAmount = 0;
      if (coins != null) {
         for (Solution.VendingMachine.Coin coin : coins.keySet()) {
            Integer count = coins.get(coin);
            if (count != null && count.intValue() > 0) {
               totalAmount += (count.intValue() * coin.getValue());
            }
         }
      }
      return totalAmount;
   }


   /**
    * The Vending Machine Interface (please do not alter this interface)
    * A coin-operated machine to automate the sale and dispensing of items to a customer.
    */
   public interface VendingMachine {

      /**
       * The restock method is intended to be used by the machine owner to
       * stock item inventory and/or coin inventory into the vending machine.
       * This method may be invoked more than once in the life-cycle of an
       * instance.
       * @param items - the products to add the product inventory
       * @param funds - the coins to add to the coin inventory
       */
      public void restock(Collection<Product> items, Collection<Coin> coins);

      /**
       * The vend method is the principle purchase method. It returns the
       * amount of change in cents when able to vend. When unable to vend for
       * any reason this method returns the full amount tendered.
       * Money tendered less any change becomes funds if and only if able to
       * vend.
       * This method may be invoked more than once in the life-cycle of an
       * instance.
       * @param itemName - the name of the product desired to purchase
       * @param tender - the coins offered for payment
       * @return change (if due) in coins (or an empty collection) when no
       *         change is due and the full tender amount when unable to vend.
       */
      public VendResult vendItem(String itemName, Collection<Coin> tender);

      /**
       * Inquires for the product inventory
       * @return the current state of product inventory or null when no
       *         products exist.
       */
      public Map<String, Integer> getItemCount();

      /**
       * Inquires for the funds inventory
       * @return the current state of the funds inventory or null when no
       *         funds exist.
       */
      public Map<Coin, Integer> getCoinCount();


      /**
       * Coin Enum - US based currency Each token represents a kind of coin
       * and its value, in cents (USD). Note: Penny(1) //$0.01 is
       * intentionally not defined
       */
      public enum Coin {
         DOLLAR(100), // $1.00
         QUARTER(25), // $0.25
         DIME(10), // $0.10
         NICKEL(5); // $0.05

         int cents = 0;

         Coin(int cents) {
            this.cents = cents;
         }

         public int getValue() {
            return cents;
         }
      };


      /**
       * The Product Class (please do not alter this class)
       * A Product represents an item to vend. Vend items have a name and price.
       * Prices for an item are instance controlled by Product name.
       * All items with the same name have the same price.
       */
      public static final class Product {

         private static final Map<String, Integer> priceMap = new HashMap();

         private final String itemName;

         Product(String itemName, int price) {
            this.itemName = String.valueOf(itemName);
            priceMap.put(itemName, Integer.valueOf(price));
         }

         public String getItemName() {
            return itemName;
         }

         public int getPrice() {
            return priceMap.get(itemName).intValue();
         }

         @Override public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((itemName == null) ? 0 : itemName.hashCode());
            return result;
         }

         @Override public boolean equals(Object obj) {
            if (this == obj)
               return true;
            if (obj == null)
               return false;
            if (getClass() != obj.getClass())
               return false;
            Product other = (Product)obj;
            if (itemName == null) {
               if (other.itemName != null) {
                  return false;
               }
            } else if (!itemName.equals(other.itemName)) {
               return false;
            }
            return true;
         }

         @Override public String toString() {
            return "Product [itemName=" + itemName + ", price=" + getPrice() + "]";
         }

      }


      /**
       * VendResult (please do not alter this class)
       * Captures the results of a vend attempt.
       * @item - the item purchased
       * @change - the coins returned
       */
      public static final class VendResult {
         private final Product item;
         private final Collection<Coin> change;

         public VendResult(Product product, Collection<Coin> change) {
            this.item = product;
            this.change = change;
         }

         public Product getItem() {
            return item;
         }

         public Collection<Coin> getChange() {
            return change;
         }
      }
   }


   /***********************************************
    * VendingMachineImpl. Code your solution here!
    ***********************************************/
   public static class VendingMachineImpl implements VendingMachine {
        private static Map<Coin, Integer> Coins = new HashMap();
        private static Map<String, Integer> inventory = new HashMap();

      // $TODO - replace this line; define any instance variables, e
      @Override public void restock(Collection<Product> items, Collection<Coin> coins) {
         // $TODO - replace this line; implement restock
         
          
          
      }

      @Override public VendResult vendItem(String itemName, Collection<Coin> tender) {
         // $TODO - replace this line; implement vendItem
          
      }

      @Override public Map<String, Integer> getItemCount() {
         // $TODO - replace this line; implement getItemCount
          if(inventory.isEmpty()){
             return null;
          }
          else{
              return inventory;
          }
          
          
      }

      @Override public Map<Coin, Integer> getCoinCount() {
         // $TODO - replace this line; implement getCoinCount
          if(Coins.isEmpty()){
             return null;
          }
          else{
              return Coins;
          }
      }

      // $TODO - replace this line; define any helper methods if/as needed.

   }

}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

因此,您想要在restock方法中执行的操作(所有其他方法都是模拟的)是将Products添加到广告资源中,以及硬币。那它会是什么样子?

private static Map<Coin, Integer> Coins = new HashMap();
private static Map<String, Integer> inventory = new HashMap()
@Override 
public void restock(Collection<Product> items, Collection<Coin> coins) {
  for(Product item : items) {
    int quantity = inventory.get(item.getItemName());
    inventory.put(item.getItemName(), inventory.get(item.getItemName()) + 1);
  }
  for(Coin coin : coins) {
    Coins.put(coin, coin.get(coin) + 1);
  }
}

文档不是很好。

  /**
   * The restock method is intended to be used by the machine owner to
   * stock item inventory and/or coin inventory into the vending machine.
   * This method may be invoked more than once in the life-cycle of an
   * instance.
   * @param items - the products to add the product inventory
   * @param funds - the coins to add to the coin inventory
   */

我没有说每次补货时是否要添加多个物品或硬币。您可能想与老师澄清这一点。但我希望你明白这一点。