Groovy - 类型测试?
我对 Groovy 还很陌生,我正在努力完成一些事情。我编写了一些 Groovy 代码(工作得很好),它接收一些文本。该文本应该是一个整数(0 到 10 之间)。可能只是用户输入了不同的内容。在这种情况下,我想做一些特定的错误处理。
现在我想知道,测试字符串类型变量是否可以转换为整数的最佳/最常规方法是什么?
(我想要做的是要么消耗字符串中的整数,要么将计算结果设置为 0。
谢谢!
I'm really brand new to Groovy and I'm trying to get something done. I've written some Groovy code (which works just fine) which receives some text. This text should be an integer (between 0 and 10). It may just happen a user enters something different. In that case I want to do some specific error handling.
Now I'm wondering, what's the best / grooviest way to test if a string-typed variable can be casted to an integer?
(what I want to do is either consume the integer in the string or set the outcome of my calculation to 0.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
String 类有一个可以使用的
isInteger()
方法:The String class has a
isInteger()
method you could use:使用 groovy 包含
use groovy contains
你是说这个吗?
Is this what you're saying?
在 groovy 中可以通过很多方法来完成此操作,如果您对正则表达式感到满意,这大约是您能得到的最简洁的:
如果用户这样做,我有点不确定“特定错误处理”是什么意思不同的东西。
如果这是一个 Web 应用程序,我会看一下 grails 以及您可以对域对象的字段施加的约束,这将让您轻松表达您想要执行的操作。
There are lots of ways this can be done in groovy, if you're comfortable with regular expressions, this is about as concise as you can get:
I'm a little unsure what you mean by "specific error handling" if the user does something different.
If this is a web application, I'd take a look at grails and the constraints that you can put on the fields of a domain object, that would let you easily express what you're trying to do.
您的问题上有
grails
标记,因此如果您使用 Grails,您可能会考虑将其设为域类上的 Integer 属性。参数可能以文本形式出现,但您可以将其绑定到默认值为 0 的整数属性:You have the
grails
tag on your question, so if you are using Grails, you might consider making this an Integer property on a domain class. The param may come in as text, but you can bind it to an integer property with a default value of 0: