2016-09-24 38 views
1

所以我需要在Smalltalk的愷撒密碼的代碼,並創建一個方法,並使用它,所以我可以做下面的測試就可以了創建愷撒密碼方法

|aString| 
aString:=Caesar new encrypt: 'CAESAR'. 
Transcript show: aString. 

我已經類製造。但我需要制定它的方法。

我發現這個,但我怎麼能做出這個方法,所以我可以在操場上面的所有代碼。

| i c strCipherText strText iShiftValue iShift | 

strText := 'the quick brown fox jumps over the lazy dog'. 
iShiftValue := 3. 

strCipherText := ''. 
iShift := iShiftValue \\ 26. 

i := 1. 
[ i <= (strText size) ] 
whileTrue: [ 
    c := (strText at: i) asUppercase. 

    ((c >= $A) & (c <= $Z)) 
    ifTrue: [ 

    ((c asciiValue) + iShift > $Z asciiValue) 
    ifTrue: [ 
     strCipherText := strCipherText, (((c asciiValue) + iShift - 26) 
         asCharacter asString). 
    ] 
    ifFalse: [ 
     strCipherText := strCipherText, (((c asciiValue) + iShift) 
         asCharacter asString). 
    ]. 

    ] 
    ifFalse: [ 
    strCipherText := strCipherText, ' '. 
    ]. 

    i := i + 1. 
]. 

Transcript show: strCipherText. 
Transcript cr. 

因此,爲了使事情清楚,我需要使用愷撒密碼碼的方法,並在一開始就使用「ASTRING」的代碼,並與測試。我在上面有這個代碼,但是它已經有了文本,並且不能被放入方法中。

任何幫助將不勝感激。

+0

當然,你可以把它放到一個方法。只需用方法參數替換'strText'即可。例如:該方法可能被稱爲'#myCaesorCodeOf:'並帶有一個名爲'aString'的參數。 –

+0

@MaxLeske我是新來的使用pharo和小談話,所以我真的不知道該怎麼做。 –

回答

2

正如Max在評論中所說的,上面的代碼可以放在一個方法中。唯一缺少的部分是選擇和正式參數第一行:

caesarCipherOf: strText 
    <insert the code here> 

由Max另一個很好的建議是調用參數aString而不是strText,因爲這是多與如何Smalltalkers名稱事情對齊。

但是,現在讓我們來看看源代碼本身:

  1. 比較c >= $A & (c <= $Z)意味着c isLetter
  2. 下一個字符的條件計算意味着我們想要通過將c移動到3字符向右移動,如果它超出$Z,則將其包圍。這可以容易地表示爲:

    (c codePoint - 64 + 3 \\ 26 + 64) asCharacter 
    

    其中64 = $A codePoint - 1,是$A和任何給定的大寫字符c之間的偏移。還請注意,我用codePoint替換了asciiValue

有了這兩個觀測方法可以重新寫成

caesarCipherOf: aString 
     ^aString collect: [:c | 
     c isLetter 
      ifTrue: [(c asUppercase codePoint - 64 + 3 \\ 26 + 64) asCharacter] 
      ifFalse: [$ ]] 

這不僅是短,更有效,因爲它避免了在每一個角色作成的String 新實例。具體而言,形式

string := string , <character> asString 

的任何表達創建兩個Strings:一個作爲發送#asString,另一個爲發送所述級聯消息#,的結果的結果。相反,#collect:只創建一個實例,即該方法返回的實例。

+0

謝謝我得到它的工作! –