0
我開始學習常規,因爲我喜歡通過實踐學習我寫了一個小的應用程序:爲什麼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」打印我的樓層詞典時,值有... 有任何想法嗎? 謝謝
太棒了!你是男人!謝謝! – 2012-03-14 16:10:47
等價的一行是:'(1..4).each {floors [it as String] =「Floor $ {it}:」}'。 – epidemian 2012-03-14 16:18:22
@epidemian我喜歡:'floor <<(1..4)*。toString()。collectEntries {[(it):「Floor $ {it}:」]}';-) – 2012-03-14 16:31:46