为什么groovy在字典中看不到一些值? [英] Why groovy does not see some values in dictionary?

查看:213
本文介绍了为什么groovy在字典中看不到一些值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习groovy,因为我喜欢通过练习学习,所以我写了这个小应用程序:

I started learning groovy, and since I like learning by practice I have written that small app:

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打印我的楼层词典时,值就在那里。 ..
任何想法?
谢谢

Everything works fine except printing on which floor you are (prompt function). It prints if you are in basement, ground floor or penthouse, but doesn't pick up "Floor i: " and prints null instead:/ When I type "pf" to print my floors dictionary, values are there... Any ideas? Thanks

推荐答案

您将 GString 实例添加为键,然后使用 String 实例搜索它们。

You're adding GString instances as keys in your map, then searching for them using String instances.

这两个不一样相同的外观 - 参见GStrings不是字符串一节 on this

The two are not the same (despite having the same appearance -- see "GStrings aren't Strings" section on this page)

尝试改变:

Try changing:

(1..4).each{floors += ["${it}" : "Floor ${it} : " ] }

(1..4).each{floors += [ ("${it}".toString()): "Floor ${it} : " ] }

这篇关于为什么groovy在字典中看不到一些值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆