Help us understand the problem. What is going on with this article?

Kotlin でシーザー暗号をつくってみた

需要は全くありませんがKotlinのクラスの練習でシーザー暗号を書いてみました
インスタンス生成のときにシフトする数を指定できます。
そしてクラス内の関数で暗号化と復号をするという感じです。
コードは我ながら汚いですがご愛嬌

caesar.kt
 class Caesar(var shiftnum : Int){
     init {
         print("this is $shiftnum shift Caesar cipher \n")
     }

     fun enc(s:String){
         var Sentence_enc = mutableListOf<Char>()
         print("Ciphertext is : ")
         for (i in 0..s.length-1) {
             Sentence_enc.add(s[i] - shiftnum)
             print(Sentence_enc[i])
         }
         Sentence_enc.clear()
         print("\n")
     }

     fun dec(s:String){
         var Sentence_dec = mutableListOf<Char>()
         print("Decryption is : ")
         for (i in 0..s.length-1) {
             Sentence_dec.add(s[i] + shiftnum)
             print(Sentence_dec[i])
         }
         Sentence_dec.clear()
         print("\n")
     }
 }

実行結果

jikkou.kt
val test = Caesar(13)
test.enc("hello")
test.dec("[X__b")
this is 13 shift Caesar cipher 
Ciphertext is : [X__b
Decryption is : hello

追記(同日)

@sdkei さんのご指摘でコードの冗長な部分を一部修正しました。
一応自分の知識にあるもので簡単に、、、ほんの少し、スッキリしたと思います。
以下に修正したコードを再掲載します。
@sdkei さん貴重なフィードバックありがとうございました。

caesar.kt
 class Caesar(val shiftnum : Int){
     val Sentence = mutableListOf<Char>()
     init {
         println("this is $shiftnum shift Caesar cipher")
     }
     fun enc(s:String){
         for (i in 0 until s.length) Sentence.add(s[i] - shiftnum)
         println("Ciphertext is : ${Sentence.joinToString("")}")
         Sentence.clear()
     }

     fun dec(s:String){
         for (i in 0 until s.length) Sentence.add(s[i] + shiftnum)
         println("Decryption is : ${Sentence.joinToString("")}")
         Sentence.clear()
     }
 }

fun main() {
    val test = Caesar(13)
    test.enc("hello")
    test.dec("[X__b")
}

実行結果

this is 13 shift Caesar cipher
Ciphertext is : [X__b
Decryption is : hello

まとめ

もっと綺麗にかけるようにがんばります
勉強不足!

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした