2010-08-30 47 views
3

我想将“Prompter prompt:aStringPrompt”中的输入值转换为整数值,我该怎么做?字符串转为小写整数

+0

在发布我的答案后,我注意到这可能是重复的http://stackoverflow.com/questions/2226029 – 2010-08-30 08:10:28

+0

可能重复的[String to Integer Smalltalk](http://stackoverflow.com/questions/2226029/string-to-integer-smalltalk) – Mark 2013-01-26 19:33:21

回答

5

两个步骤:(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. 
+0

先生在海豚怎么样,我不使用吱吱声。你能用海豚语法来解释吗?非常感谢 – leroj 2010-08-30 08:19:40

+0

aString asInteger应该适用于所有的Smalltalks。最好的方法是尝试一下,看看你的Smalltalk方言的类库,以找出所有的可能性。 – 2010-08-30 10:19:58

+0

@Frank Shearar,感谢您的链接,但我仍然解决了我的问题。输入对话框出现后,我输入了我的号码,但它不会将其更改为asInteger或asNumber变量。我的问题是我宣布我的随机数它不会改变它在这里是我的代码请评论它,如果你有一个想法如何解决它谢谢 – leroj 2010-08-31 01:04:00

1

在海豚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'. 

这也运行得很好,有额外的好处,它不会接受非数字字符。

分享和享受。