我开始学习groovy,因为我喜欢通过练习学习,所以我写了那个小应用程序:
def height = 1; def commands; def floors; def finished = false
def up = { height < 5 ? height++ : println("Can't go higher!") }
def down = { height > -1 ? height-- : println("Can't go lower!") }
def help = {
print "Commands are "
commands.each{key, val -> print "'$key' "}
println()
}
def printFloors = {
println "Floors are "
floors.each{key,val -> println "'$key' -> '$val'"}
println()
}
def exit = { finished = true }
def prompt = { print floors["$height"] }
commands = [ 'u': up,
'up': up,
'd': down,
'down': down,
'help': help,
'': help,
'exit': exit,
'pf': printFloors]
floors = [ "-1": "Basement : " ,
"0": "Ground : " ,
"5": "Penthouse : " ]
(1..4).each{floors += ["${it}" : "Floor ${it} : " ] }
bR = new BufferedReader(new InputStreamReader(System.in))
while(!finished){
prompt()
def cmd = bR.readLine()
def code = commands[cmd]
if(code != null){
code()
}
}
除了打印你所在的楼层(提示功能)外,一切正常。如果你在地下室,底层或顶层公寓,它会打印,但不会选择“Floor i:”并打印null而不是:/ 当我输入“pf”打印我的楼层词典时,值就在那里...... 有任何想法吗? 感谢
答案 0 :(得分:7)
您正在将GString
个实例添加为地图中的关键字,然后使用String
个实例进行搜索。
两者不一样(尽管外观相同 - 请参阅“GStrings不是字符串”部分on this page)
尝试更改:
(1..4).each{floors += ["${it}" : "Floor ${it} : " ] }
到
(1..4).each{floors += [ ("${it}".toString()): "Floor ${it} : " ] }