i want to convert the input value in "Prompter prompt: aStringPrompt" into a integer value, how can i do that?
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:
"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.
Just tried this in Dolphin 6:
(Prompter prompt: 'Enter a number') asInteger
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:
| 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'.
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:
| 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'.
This also ran fine, with the added benefit that it won't accept non-numeric characters.
Share and enjoy.