-3

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

  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

但是它不起作用,我不知道为什么?

4

2 回答 2

0

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

于 2012-12-14T19:34:40.367 回答
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
于 2012-12-14T19:02:24.157 回答