【问题标题】:Adding quantities of Duplicate Strings添加数量的重复字符串
【发布时间】:2014-09-05 17:52:10
【问题描述】:

我的任务是对类别列表进行排序。一份购物清单,如果你愿意的话。这些类别是来自用户的输入,要购买的物品。在输入相关类别的字符串名称后(当然使用扫描仪),用户可以输入该类别的数量(整数),然后输入该类别的单位成本(双精度)。 系统会提示他们重复此操作,直到他们命名的类别为“结束”。

这一切都很好,而且我已经编写了代码来获取所有这些信息,并找到并打印出最大成本项目、最大数量项目和其他信息。我需要帮助的是我的重复类别。例如,假设用户输入“cars”,后跟一个整数 3,然后是数字 24000.00。然后他们放入“refigerators”,然后是 1,然后是 1300.00。然后用户输入第一个条目的副本,即“汽车”,后跟整数 5,然后是双精度 37000.00。如何让我的代码重新访问旧条目,将新数量添加到旧条目中,并在不覆盖旧条目的情况下存储该值?我还需要找到列表中项目的最大平均成本。我是 HashMap 的新手,所以我在代码中苦苦挣扎://创建一个 arrayList 来存储值

              // create an arrayList to store values

            ArrayList<String> listOne = new ArrayList<String>();

            listOne.add("+ 1 item");

            listOne.add("+ 1 item");

            listOne.add("+ 1 item");



            // create list two and store values

            ArrayList<String> listTwo = new ArrayList<String>();

            listTwo.add("+1 item");

            listTwo.add("+1 item");



            // put values into map

            multiMap.put("some sort of user input detailing the name of the item", listOne);

            multiMap.put("some other input detailing the name of the next item", listTwo);
            // i need the user to input items until they type "end"

            // Get a set of the entries

            Set<Entry<String, ArrayList<String>>> setMap = multiMap.entrySet();

            // time for an iterator
            Iterator<Entry<String,  ArrayList<String>>> iteratorMap = setMap.iterator();        

           System.out.println("\nHashMap with Multiple Values");

            // display all the elements
                while(iteratorMap.hasNext()) {

                Map.Entry<String, ArrayList<String>> entry =

                        (Map.Entry<String, ArrayList<String>>) iteratorMap.next();

                String key = entry.getKey();

                List<String> values = entry.getValue();

              System.out.println("Key = '" + key + "' has values: " + values);

            }
    // all that up there gives me this: 

具有多个值的 HashMap Key = 'some other input detailing the name of the next item' 具有值:[+1 项,+1 项] Key = '某种详细说明项目名称的用户输入' 具有值:[+ 1 项,+ 1 项,+ 1 项]

但我没有给用户输入物品数量或成本的机会……我迷路了。

【问题讨论】:

  • Set 仅存储唯一值,因此当您从 multiMap.entrySet 获取 setMap 时会出现问题。因为你有相同的价值,它们只会被存储一次......
  • “我还需要找到最大的平均成本”是什么意思?什么的平均值?
  • 这意味着如果我有:鸡蛋 1 7.00,牛奶 1 1.99,鸡蛋 2 2.50,那么程序应该打印出鸡蛋具有最大的平均成本项目:即 (7+5)/ 3 = 4
  • 我的答案中的示例代码是否解决了您正在查看的问题?

标签: java arraylist hashmap


【解决方案1】:

试试这个小示例代码,它包括一个 Main 类和两个依赖类,StatsPrinter 和 ShoppingEntry

package com.company;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        String category;
        String quantity;
        String value;

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        HashMap<String, List<ShoppingEntry>> shoppingList = new HashMap<String, List<ShoppingEntry>>();

        while(true) {
            System.out.print("Enter the category of your item: ");
            category = bufferedReader.readLine();

            if("end".equals(category)){
                break;
            }

            System.out.print("Enter the quantity of your item: ");
            quantity = bufferedReader.readLine();

            System.out.print("Enter the value of your item: ");
            value = bufferedReader.readLine();

            if (shoppingList.containsKey(category)) {
                shoppingList.get(category).add(new ShoppingEntry(Integer.parseInt(quantity), Double.parseDouble(value)));
            }else{
                shoppingList.put(category, new ArrayList<ShoppingEntry>());
                shoppingList.get(category).add(new ShoppingEntry(Integer.parseInt(quantity),          Double.parseDouble(value)));
            }
        }

        StatsPrinter.printStatistics(shoppingList);
    }
}

还有 ShoppingEntry 类

package com.company;

public class ShoppingEntry {
    private int quantity;
    private double price;

    public ShoppingEntry(){
        quantity = 0;
        price = 0;
    }

    public ShoppingEntry(int quantity, double price){
        this.quantity = quantity;
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

最后是 StatsPrinter 类,它利用 ShoppingEntry 的 HashMap 的数据结构来打印所需的统计信息

package com.company;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;

public class StatsPrinter {
    private static DecimalFormat format = new DecimalFormat("#.##");

    public static void printStatistics(HashMap<String, List<ShoppingEntry>> shoppingList) {
        printNuumberOfItems(shoppingList);
        printLargestValue(shoppingList);
        printLargestAverage(shoppingList);
    }

    private static void printNuumberOfItems(HashMap<String, List<ShoppingEntry>> shoppingList) {
         System.out.println("There are " + shoppingList.keySet().size() + " items in your Shopping List");
     }

    private static void printLargestValue(HashMap<String, List<ShoppingEntry>> shoppingList) {
        double currentLargestPrice = 0;
        String largestPriceCategory = new String();

        for(String keyValue : shoppingList.keySet()) {
            for(ShoppingEntry entry : shoppingList.get(keyValue)) {
                if (entry.getPrice() > currentLargestPrice) {
                    currentLargestPrice = entry.getPrice();
                    largestPriceCategory = keyValue;
                }
            }
        }

        System.out.println(largestPriceCategory + " has the largest value of: " +      format.format(currentLargestPrice));
     }

    private static void printLargestAverage(HashMap<String, List<ShoppingEntry>> shoppingList) {
        double currentLargestAverage = 0;
        String largestAverageCategory = new String();
        double totalCost = 0;
        int numberOfItems = 0;

        for(String keyValue : shoppingList.keySet()) {
            for(ShoppingEntry entry : shoppingList.get(keyValue)) {
                totalCost += entry.getPrice();
                numberOfItems += entry.getQuantity();
            }
            if((totalCost / numberOfItems) > currentLargestAverage) {
                currentLargestAverage = totalCost / numberOfItems;
                largestAverageCategory = keyValue;
            }
        }

        System.out.println(largestAverageCategory + " has the largest average value of: " +     format.format(currentLargestAverage));
    }
}

【讨论】:

    【解决方案2】:

    创建一个名为Item 的类,而不是操作三个单独的值。实现Comparable 接口,这样如果两个项目共享一个通用名称,则它们是相等的。有关定义接口的说明,请参阅Javadoc for Comparable

    public class Item implements Comparable { 
        [...] 
    }
    

    创建一个项目列表。

    List<Item> shoppingList;
    

    当你想向列表中添加一个项目时,首先检查列表是否已经包含它。

    // If it's already in the list, add their quantities together
    if (shoppingList.contains(newItem))
        shoppingList.get(newItem).quantity += newItem.quantity
    // Otherwise, add it to the list
    else
        shoppingList.add(newItem);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-26
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多