簡體   English   中英

我如何在Smalltalk中換行?

[英]How can i get a new line in smalltalk?

我想使用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中獲得新的一行

嘗試以下代碼。

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

回答您的問題:Transcript cr獲得一個換行符,該換行符隨后將其發送給Character cr。

您可以創建一個帶有單個回車符的字符串

(String with: Character cr)

但是您應該學習如何使用Stream而不是連接字符串,請參閱消息writeStream,#nextPut:,#nextPutAll:和類WriteStream

編輯我不想提供現成的解決方案,但是由於您有很多其他解決方案,因此這里可能會堅持使用字符串。 我認為#out如您的問題所示會生成自己的CR。 然后,我自己的解決方案是#inject:into:累積而不是在每個循環中重新創建整個String:

(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更高的Collection迭代器開辟一些視角:

| max resultString |
max := 5 .
resultString := String new.
1 to: max do: [ :line |
    1 to: line do: [ :number |
        resultString add: number asString, ' '
    ].
    resultString lf.
].
resultString

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM