两个步骤:(a)验证输入,(b)转换.
你可以这样验证:myString isAllDigits.
转换是微不足道的:'1' asInteger.至少在Squeak中,它返回整数1. 'g1' asInteger返回1,同样如此'g1' asInteger.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.
Run Code Online (Sandbox Code Playgroud)