添加重复字符串的数量

时间:2014-09-05 17:52:10

标签: java arraylist hashmap

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

这一切都很好,花花公子,我已经编写了代码,可以获取所有这些信息,并找到并打印出最大的成本项目,最大数量的项目和其他信息。我需要帮助的是我的重复类别。例如,假设用户输入“cars”后跟一个整数3,后跟数字24000.00。然后他们输入“refigerators”,然后是1,然后是1300.00。然后用户输入第一个条目的副本,即“cars”后跟一个整数5,然后是double 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 ='详细说明下一个项目名称的其他一些输入'具有值:[+ 1项目,+ 1项目] Key ='详细说明项目名称的某种用户输入'具有值:[+ 1项,+ 1项,+ 1项]

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

2 个答案:

答案 0 :(得分:0)

创建一个名为Item的类,而不是操纵三个单独的值。实现Comparable接口,如果它们共享一个公用名,则两个Items相等。有关定义界面的说明,请参阅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);

答案 1 :(得分:0)

尝试这一小段示例代码,它包含一个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));
    }
}