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);

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

4

1 回答 1

1
if (button == "Search") 

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

if(button.equals("Search")) 

参考

你应该输入种姓地图

HashMap wordMap = new HashMap();

   Map<Object,Object> wordMap =new HashMap<Object,Object>();

现在在你的代码中

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

我认为您的 dicionarymap 正在返回一个对象,但您将其设置为字符串。您需要先将对象转换为字符串。

于 2013-07-14T15:01:47.833 回答