1

我想使用 smalltalk 代码以以下格式显示数字

     1
     1 2
     1 2 3
     1 2 3 4

我写了以下代码

| i j y k |
i :=1.
j :=1.
y:= ('y' at: 1 put: $ )out.

(i<=4)ifTrue: [
i to: 4 by:1 do:[:i |


     (j<=i)ifTrue: [
     j to: i by: 1 do:[:j |

         ( j print++y print)out.

         ]
            ]

     ]
]

当我执行上述程序时,它以下列格式显示数字

输出:

1 ' '
1 ' '
2 ' '
1 ' '
2 ' '
3 ' '
1 ' '
2 ' '
3 ' '
4 ' '

谁能帮助我以金字塔格式显示输出以及在 smalltalk 中获取新行的方法

4

3 回答 3

5

试试下面的一段代码。

|n|
Transcript cr.
n := 4.
1 to: n do: [:i |
    1 to: i do: [:j |
        Transcript show: j].
    Transcript cr].

要回答您的问题:您会通过 Transcript cr 获得一个换行符,然后将其发送给 Character cr。

于 2012-12-18T12:44:33.000 回答
2

您可以使用单个回车符创建一个字符串

(String with: Character cr)

但是您应该学习如何使用Stream而不是连接字符串,请参阅消息 writeStream、#nextPut:、#nextPutAll: 和类 WriteStream

编辑我不想提供现成的解决方案,但是由于您还有很多其他解决方案,所以这里可能会坚持使用字符串。正如您的问题所暗示的那样,我认为 #out 会生成自己的 CR。然后我自己的解决方案是 #inject:into: 累积而不是在每个循环中重新创建整个字符串:

(1 to: 4) inject: String new into: [:str :num |
    (str , num printString , ' ') out; yourself]

或使用传统的成绩单:

(1 to: 4) inject: String new into: [:str :num |
    | newStr |
    newStr := str , num printString , ' '.
    Transcript cr; show: newStr.
    newStr]

我希望它打开一些关于更高级别的集合迭代器的观点,而不是愚蠢的#to:do:

于 2012-12-18T12:38:41.080 回答
0
| max resultString |
max := 5 .
resultString := String new.
1 to: max do: [ :line |
    1 to: line do: [ :number |
        resultString add: number asString, ' '
    ].
    resultString lf.
].
resultString
于 2012-12-18T13:22:08.710 回答