我想将“Prompter prompt:aStringPrompt”中的输入值转换为整数值,我该怎么做?字符串转为小写整数
回答
两个步骤:(a)验证输入,并(b)转换。
您可以这样验证:myString isAllDigits
。
转换是微不足道的:'1' asInteger
。在Squeak中,至少返回整数1. 'g1' asInteger
返回1,'g1' asInteger
也返回1。 g asInteger
返回零。
所以:
"Given some input string s containing a decimal representation of a number, either return s in integer form, or raise an exception."
s := self getUserInput.
(s isAllDigits) ifFalse: [ Exception signal: '"', s, '" is not a (decimal) number' ].
^ s asInteger.
先生在海豚怎么样,我不使用吱吱声。你能用海豚语法来解释吗?非常感谢 – leroj 2010-08-30 08:19:40
aString asInteger应该适用于所有的Smalltalks。最好的方法是尝试一下,看看你的Smalltalk方言的类库,以找出所有的可能性。 – 2010-08-30 10:19:58
@Frank Shearar,感谢您的链接,但我仍然解决了我的问题。输入对话框出现后,我输入了我的号码,但它不会将其更改为asInteger或asNumber变量。我的问题是我宣布我的随机数它不会改变它在这里是我的代码请评论它,如果你有一个想法如何解决它谢谢 – leroj 2010-08-31 01:04:00
在海豚6只是尝试这样做:
(Prompter prompt: 'Enter a number') asInteger
运行此(在上述地方光标在一个工作区,并点击Ctrl-d),在输入123出现的提示符,您将看到123作为输出显示。如果删除#asInteger调用,它将显示“123”,表示已返回字符串。
至于你'不理解#number',这意味着你正在运行#number消息的代码中的某处发送给一个不知道如何处理它的对象。
对于它的乐趣我把你的代码,并稍微重新格式化它:
| dir |
[ dir isNil or: [ dir isEmpty ] ] whileTrue:
[ dir:= Prompter prompt: 'Enter your number' caption: 'Input the Number' ].
MessageBox notify: 'your inputed number is ', (dir) caption: 'Inputed'.
,发现它运行得很好。这时我才发现它没有返回的字符串转换为数字,所以我把它改为:
| dir |
[ (dir isNil or: [ dir isEmpty ]) or: [ (dir select: [ :c | c isDigit not ]) size > 0 ] ] whileTrue:
[ dir:= Prompter prompt: 'Enter your number' caption: 'Input the Number' ].
MessageBox notify: 'your inputed number is ', (dir) caption: 'Inputed'.
这也运行得很好,有额外的好处,它不会接受非数字字符。
分享和享受。
- 1. C# - 将小数转换为整数的字符串
- 2. 将小数点后的字符串转换为整数
- 3. Java如何将小写字符串值转换为字符串数组中的大写字符串
- 4. 整数转换为字符串?
- 5. 将字符串转换为整数
- 6. 将字符串转换为整数
- 7. 从字符串转换为整数
- 8. 字符串转换为整数
- 9. 字符串转换为整数
- 10. Python将字符串转换为整数?
- 11. 将字符串转换为整数C#
- 12. 转换整数列表为字符串
- 13. Swift:将字符串转换为整数
- 14. 将字符串转换为整数
- 15. 将字符串转换为整数
- 16. 将字符串转换为大整数?
- 17. 字符串转换 '十' 为整数10
- 18. 将字符串转换为整数?
- 19. 转换字符串为整数错误
- 20. Java将字符串转换为整数
- 21. 将整数转换为字符串
- 22. 将字符串转换为整数
- 23. 将整数转换为字符串
- 24. 将字符串转换为整数
- 25. “字符串不能转换为整数”
- 26. BestPractice - 将字符串的第一个字符转换为小写
- 27. 转移整数字符串
- 28. 将小端字符串转换为整数
- 29. 将字符串数组转换为小写
- 30. 将字符串数组元素转换为小写
在发布我的答案后,我注意到这可能是重复的http://stackoverflow.com/questions/2226029 – 2010-08-30 08:10:28
可能重复的[String to Integer Smalltalk](http://stackoverflow.com/questions/2226029/string-to-integer-smalltalk) – Mark 2013-01-26 19:33:21