检查地图中的键

时间:2012-12-14 18:19:48

标签: java

我有这个方法,它应该检查一个键是否在一个映射中,然后增加一个值。

  papers.add(paper); //add a paper to the paper collection
    papersOrdered.get(papers); //returns the papers
    if(!(papersOrdered.containsKey(paper))) {
        paperNo = 1;
        String noPaper = Integer.toString(paperNo); //convert the paperNo integer to a String
        papersOrdered.put(papers,noPaper); //put the rooNo and the paper collection into the HashMap
        System.out.println("'" + paper + "'" + " has been added to the paper order. " + noPaper + " copy ordered" ); //a message to say a paper has been added
    }
    else{
        paperNo = paperNo ++;
        String noPaper = Integer.toString(paperNo); //convert the paperNo integer to a String
        papersOrdered.put(papers,noPaper); //put the rooNo and the paper collection into the HashMap
        System.out.println("'" + paper + "'" + " has been added to the paper order." + noPaper + " copies ordered" ); //a message to say a paper has been added
    }
    System.out.println("======================================================="); ; //a line to seperate text 
    System.out.println(" "); //a blank line

然而它不起作用,我不知道为什么?

2 个答案:

答案 0 :(得分:0)

基于原始代码,但将整数放入HashMap值而不是字符串,并在为该类纸张添加新订单时递增键的当前值。

int paperNo;
String paper;
HashMap papersOrdered;
...
papers.add(paper); //add a paper to the paper collection
papersOrdered.get(papers); //returns the papers
if(!(papersOrdered.containsKey(paper))) {
    paperNo = 1;
    papersOrdered.put(papers, new Integer(paperNo)); //put the rooNo and the paper collection into the HashMap
    System.out.println("'" + paper + "'" + " has been added to the paper order. " + paperNo + " copy ordered" ); //a message to say a paper has been added
} else{
    paperNo = papersOrdered.get(paper) + 1; //get the current value, and add 1 to it
    papersOrdered.put(papers, new Integer(paperNo)); //put the rooNo and the paper collection into the HashMap
    System.out.println("'" + paper + "'" + " has been added to the paper order." + paperNo + " copies ordered" ); //a message to say a paper has been added
}
System.out.println("======================================================="); ; //a line to seperate text 
System.out.println(" "); //a blank line

答案 1 :(得分:0)

查看Google Guava的Multiset,它就是这样做的。