如何显示在ArrayList字符串中输入的每个项目的数量?

时间:2016-11-11 18:50:55

标签: java

我有ArrayList String,其中用户输入了项目数,当他们输入关键字stop时,代码会显示输入的项目数,然后显示有多少项他们的list。例如,如果我输入苹果,苹果,苹果,香蕉,停止,项目总数为4,苹果x2苹果x1香蕉x1。 我在最后一部分遇到了麻烦,它显示了输入的数量。这就是我到目前为止所拥有的 编辑:我不知道/没有使用过HashMap,我只知道使用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());
}
}

3 个答案:

答案 0 :(得分:0)

您可以轻松使用Java的HashMap对象。每个密钥都保证是唯一的,因此如果密钥已经存在,您可以增加一个密钥,或者创建一个新密钥。例如:

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();
}

答案 1 :(得分: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!");
}

答案 2 :(得分: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);


    }