Smalltalk中的字符串到整数
我想将“Prompter提示:aStringPrompt”中的输入值转换为整数值,我该怎么做?
i want to convert the input value in "Prompter prompt: aStringPrompt" into a integer value, how can i do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两个步骤:(a) 验证输入,(b) 转换。
您可以像这样进行验证:
myString isAllDigits
。转换很简单:
'1' asInteger
。至少在 Squeak 中,这会返回整数 1。'g1' asInteger
返回 1,'g1' asInteger
也是如此。g asInteger
返回 nil。总结来说:
Two steps: (a) validate the input, and (b) convert.
You could validate like so:
myString isAllDigits
.Converting is trivial:
'1' asInteger
. In Squeak, at least, this returns the integer 1.'g1' asInteger
returns 1, as does'g1' asInteger
.g asInteger
returns nil.So in summary:
刚刚在 Dolphin 6 中尝试过:
运行此命令(将光标放在工作区中的上面并按 Ctrl-D),在出现的提示中输入 123,您将看到 123 显示为输出。如果删除 #asInteger 调用,它将显示“123”,表明返回了一个字符串。
至于您的“不理解#number”,这意味着您在代码中的某个位置运行消息#number,因为该消息被发送到不知道如何处理它的对象。
为了好玩,我拿了你的代码并稍微重新格式化了它:
发现它运行得很好。然后我注意到它没有将返回的字符串转换为数字,因此我将其更改为:
这也运行良好,还有一个额外的好处,即它不接受非数字字符。
分享并享受。
Just tried this in Dolphin 6:
Run this (place cursor on the above in a workspace and hit Ctrl-D), enter 123 in the prompt that comes up, and you'll see 123 displayed as the output. If you remove the #asInteger invocation, it'll display '123', indicating that a String was returned.
As to your 'does not understand #number', that means that somewhere in the code you were running the message #number as being sent to an object that didn't know how to handle it.
For the fun of it I took your code and slightly reformatted it:
and found that it ran just fine. Then I noticed it didn't convert the returned String to a number, so I changed it to:
This also ran fine, with the added benefit that it won't accept non-numeric characters.
Share and enjoy.