我在类中构建了一个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。
答案 0 :(得分: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正在返回一个Object,但是您将其设置为String。您需要先将Object转换为String。