2012-12-14 77 views
-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 

但它不起作用,我不知道爲什麼?

+2

它以什麼方式不起作用? –

+0

如果您輸入已經在地圖中的鍵,則數字不會增加。 –

+0

'paperNo'從哪裏來?看起來你的問題是'paperNo'不是你從地圖中獲得的數字。 (另外,你爲什麼要將整數轉換成字符串和從字符串轉換整數,當你只能使用整數時?) –

回答

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 
+0

我第一次嘗試這樣的代碼,我得到一個.put錯誤,但平心而論,我認爲這也會起作用。 –

+0

錯誤說的是什麼? – jonhopkins

+0

沒有找到合適的方法put(java.util.Array,java.lang.String,int) –

0

查看Google Guava的Multiset,它完全是這樣。