原因不明的类型与错误不匹配

时间:2013-07-14 14:45:03

标签: java swing hashmap

我在类中构建了一个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);

我无法弄清楚为什么它给我的错误说:不兼容的类型它指向我的searchValue语句中的searchKey变量。 required是String,找到的是Object。

1 个答案:

答案 0 :(得分:1)

if (button == "Search") 

在上面的代码中,它的错误,在Java String中被比较为

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正在返回一个Object,但是您将其设置为String。您需要先将Object转换为String。