2016-11-11 64 views
0

我有一個ArrayListString用戶輸入物品數量,當他們輸入關鍵字stop時,代碼顯示輸入物品的數量,然後list上有多少物品。例如,如果我進入蘋果,蘋果,蘋果,香蕉,停止,項目總數是4,蘋果x2蘋果x1香蕉x1。 我在最後一部分遇到問題,它顯示輸入的數量。這是我迄今爲止 編輯:我不知道/沒有使用HashMap的,我知道最多隻能使用ArrayList的如何顯示在ArrayList字符串中輸入的每個項目的數量?

public static void main(String[] args) { 
    ArrayList<String> list = new ArrayList<String>(); 

    System.out.println("Enter the what you wish to purchase:"); 
    Scanner read= new Scanner(System.in); 
    String item = read.nextLine(); 

    while(!item.equals("stop")) { 
     list.add(item); 
     item = read.nextLine(); 
    } 
    System.out.println("Total items: " +list.size()); 
} 
} 
+0

使用HashMap 而不是ArrayList。字符串鍵是項目的名稱,例如蘋果,香蕉和整數值是購買數量 –

+0

[Word頻率計數Java 8]的可能重複(http://stackoverflow.com/questions/29122394/word-frequency-count-java-8) –

+0

有沒有辦法做*沒有*使用HashMap?這是我還沒有學到的東西,雖然在這種情況下使用起來可能更容易。 – Jessica

回答

0

您可以輕鬆地使用Java的HashMap對象。每個密鑰保證是唯一的,所以如果密鑰已經存在,你可以遞增1,或者創建一個新的密鑰。例如:

HashMap<String, Integer> map = new HashMap<String,Integer>(); 

while(!item.equals("stop")) 
{ 
    if (map.containsKey(item)) 
    { 
     // increment the value by one probably not the most effficent way 
     Integer count = map.get(item) + 1; 
     map.put(item, count); 
    } 
    else 
    { 
     map.put(item, new Integer(1)); 
    } 

    item = read.nextLine(); 
} 
0

由於您需要跟蹤它們的項目以及每個項目的計數,所以您可能需要使用HashMap代替。

Map<String, Integer> items = new HashMap<String, Integer>(); 

if (items.contains(item)) { 
    items.put(item, items.get(item) + 1); 
} else { 
    items.put(item, 1); 
} 

// print all items 
for (String s : items.keySet()) { 
    System.out.println(s); 
} 

// print quantity of each item 
for (Entry<String, Integer> entry : items) { 
    System.out.println("Item " + entry.key() + " was entered " + entry.value() + " times!"); 
} 
0

有很多方法可以做到這一點。我的解決方案基於:https://stackoverflow.com/a/15261944/1166537

public static void main(String[] args) { 
     Map<String, Integer> table = new HashMap<String, Integer>() { 

      @Override 
      public Integer get(Object key) { 
       return containsKey(key) ? super.get(key) : 0; 
      } 
     }; 

     System.out.println("Enter the what you wish to purchase:"); 
     Scanner read = new Scanner(System.in); 
     String item = read.nextLine(); 
     int itemCount = 0; 

     while (!item.equals("stop")) { 
      itemCount++; 
      table.put(item, table.get(item)+1); 
      item = read.nextLine(); 
     } 

     for(String key : table.keySet()) 
     { 
      System.out.println(key +" -> "+ table.get(key)); 
     } 
     System.out.println("Total items: " + itemCount); 


    } 
相關問題