对于Java HashMap上的每个循环 [英] For each loop on Java HashMap
问题描述
我写的一个基本的聊天程序有几个关键字,它们会产生特殊的动作,图像,消息等。我将所有关键字和特殊功能存储在HashMap中。关键词是关键和功能是价值。我想用某种类型的循环比较用户输入和键。我尝试了一切我能想到的,没有任何工作。这是我可以弄清楚的:
myHashMap =<文件输入>
for(String currentKey:< HashMap Keys列表>){
if(user.getInput()。equalsIgnoreCase(currentKey)){
//相关的值操作
}
}
...
我将不胜感激。请原谅我,如果我忽略了类似的问题,或者答案是显而易见的。
好的,你可以这样写: (字符串currentKey:myHashMap.keySet()){
但这并不是使用哈希映射的最佳方式。
更好的方法是填充 myHashMap
全部使用小写键,然后写入:
theFunction = myHashMap。得到(user.getInput()toLowerCase());
检索函数(或 null
if用户输入不会出现在地图中)。
A basic chat program I wrote has several key words that generate special actions, images, messages, etc. I store all of the key words and special functions in a HashMap. Key words are the keys and functions are the values. I want to compare user input to the keys with some type of loop. I have tried everything I can think of and nothing works. This is what I can figure out:
myHashMap = <File Input>
for(String currentKey : <List of HashMap Keys>){
if(user.getInput().equalsIgnoreCase(currentKey)){
//Do related Value action
}
}
...
I would appreciate any help. Forgive me if I overlooked a similar question or if the answer is obvious.
解决方案 Well, you can write:
for(String currentKey : myHashMap.keySet()){
but this isn't really the best way to use a hash-map.
A better approach is to populate myHashMap
with all-lowercase keys, and then write:
theFunction = myHashMap.get(user.getInput().toLowerCase());
to retrieve the function (or null
if the user-input does not appear in the map).
这篇关于对于Java HashMap上的每个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!