String to integer in smalltalk

I want to convert the input value in "Prompter Request: aStringPrompt" to an integer value, how can I do this?

+3
source share
2 answers

Two steps: (a) verify the input and (b) convert.

You can argue as follows: myString isAllDigits.

Conversion is trivial: '1' asInteger. In Squeak, at least this returns the integer 1. 'g1' asIntegerreturns 1, like 'g1' asInteger. g asIntegerreturns nil.

So in short:

"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.
+5
source

Just tried this in Dolphin 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

Source: https://habr.com/ru/post/1762235/


All Articles