我想解析一个命令和一个整数,使"turtle"在棋盘上移动。我有点不知所措,因为它没有抛出异常,我甚至无法弄清如何在没有异常的情况下打开调试器。
我的代码:
"only should begin parsing on new line"
endsWithNewLine:= aTurtleProgram endsWith: String cr.
endsWithNewLine ifTrue:[
"splits commands based on new lines"
commands := aTurtleProgram splitOn: String cr.
commands do:[:com |
"should split into command and value for command"
i := com splitOn: ' '.
"command"
bo := ci at: 1.
val := ci at: 2.
"value for command"
valInt := val asInteger.
^ bo = 'down' "attempted switch"
ifTrue: [ turtle down: valInt ]
ifFalse: [
bo = 'left'
ifTrue: [ turtle left: valInt ]
ifFalse: [
bo = 'right'
ifTrue: [ turtle right: valInt ]
ifFalse: [
bo = 'up'
ifTrue: [ turtle up: valInt ]
ifFalse: [ self assert: false ] ] ] ] ].
(bo, ':') asSymbol
或bo asSymbol asMutator
。 - Tobiasswitch
语句的原因是很容易创建一小组对象层次结构并让它们管理条件行为。这就是GoF所谓的“状态模式”,旨在使代码比许多条件语句更易于维护。(当然,字典方法仍然比使用switch
语句更好。) - Amos M. Carpenter