smalltalk

时间:2015-09-07 03:57:33

标签: smalltalk pharo

我正在尝试使用循环绘制符号链。我这样做,但它总是绘制x个圈子......

1 to: x do: [
    (self lastWasSquare)
            ifTrue: [ self drawCircle]
            ifFalse: [ self drawSquare]
]

我也尝试过:

x timesRepeat: [ 
    (self lastWasSquare)
            ifTrue: [ self drawCircle]
            ifFalse: [ self drawSquare]
]. 

但仍在画圆圈。我还尝试通过在循环中添加:n |变量并询问是否为偶数来执行此操作,但同样,它始终执行循环代码。 我究竟做错了什么? 谢谢

1 个答案:

答案 0 :(得分:3)

self lastWasSquare的来电似乎一直在返回true,以便您的#ifTrue:ifFalse:继续进入调用self drawCircle的区块。你可以:

  1. 确保您的drawCircledrawSquare方法正确设置了lastWasSquare实例变量(至少我假设这只是一个getter方法)。
  2. 将最后绘制的项目是圆形还是方形的决定移动到临时变量中。
  3. 如果您在正在处理的方法之外的任何地方需要lastWasSquare值,第一种方法会更好。第二种方式是更好的,如果它是你画圆圈或正方形的唯一地方(保持范围尽可能小)并且可能看起来像这样:

    | lastWasSquare |
    lastWasSquare := false.
    x timesRepeat: [ 
        lastWasSquare
            ifTrue: [ self drawCircle ]
            ifFalse: [ self drawSquare ].
        lastWasSquare := lastWasSquare not
    ].
    

    因此,您不断在lastWasSquaretrue之间切换false,它会绘制交替的形状。 (当我说“画一串符号”时,我假设你正在努力实现这一目标......)

    如果这些都不适用,那么,正如Uko在评论中所说,您需要发布更多代码才能让我们为您提供帮助。