2013-07-14 39 views
1

我建了一個HashMap中的一類,像這樣:不明原因的類型不匹配錯誤

public static HashMap<String, String> makeMap(String file) { 
    HashMap wordMap = new HashMap<String, String>(); 
    try { 
    Scanner dictionFile = new Scanner(new FileInputStream(file)); 

    while(dictionFile.hasNextLine()) { 
     String[] values = new String[2]; 
     values = dictionFile.nextLine().split(","); 
     wordMap.put(values[0], values[1]); 
    } 
    } catch (FileNotFoundException e) { 
    System.out.println("File not found!"); 
    } 
    return wordMap; 
}  

然後我打電話給我的makeMao功能如下:

HashMap dictionaryMap = Maintainance.makeMap("dictionary.txt"); 
    String button = e.getActionCommand(); 
    String homeUrl = "http://www.catb.org/jargon/html/"; 
    String glossUrl = "http://www.catb.org/jargon/html/go01.html"; 
    String searchedValue; 
    String completeUrl; 
    URL searchedUrl; 
    String msgPart1 = "The word you are searching for cannot be found. "; 
    String msgPart2 = "You are being rerouted to the glossary."; 
    String message = msgPart1 + msgPart2; 
    String title = "word Not Found"; 
    if (button == "Search") { 
    String searchKey = textField.getText(); 
    searchedValue = dictionaryMap.get(searchKey); 

我想不通爲什麼它是給我的錯誤說:不兼容的類型是在我的searchKey變量指向我searchedValue聲明內。需要的是String並且發現是Object。

回答

1
if (button == "Search") 

在你上面的代碼中的錯誤,在Java中字符串的比較結果爲

if(button.equals("Search")) 

Referrence

你應該輸入種姓地圖

HashMap wordMap = new HashMap(); 

Map<Object,Object> wordMap =new HashMap<Object,Object>(); 
在你的代碼

 String searchKey = textField.getText(); 
    searchedValue = dictionaryMap.get(searchKey); 

現在我覺得你dicionarymap將返回一個對象,但你將它設置爲一個String.You需要將對象先轉換爲字符串。

+0

你在暗示使用toString()方法?如果所以我試圖通過使用它說使用它: searchedValue = dictionaryMap.get(searchKey)的ToString(); 我不知道的另一種方式返回的對象轉換爲字符串。 –

+0

是的。但是,如果您爲地圖聲明瞭類型,這將是一個更好的想法。 – Makky

+0

好吧,我終於得到它使用您的諮詢工作。我感謝幫助! –