-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

元のコードに基づいていますが、文字列ではなく 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 に答える
0

Google Guava の Multiset をチェックしてください。まさにこれを行います。

于 2012-12-14T19:34:40.367 に答える