CodeGym /행동 /Kotlin SELF /Type conversions and working with Char

Type conversions and working with Char

Kotlin SELF
레벨 6, 레슨 5
사용 가능

1. Introduction

Kotlin-eul sseugi sijakhago na-myeon, gakkeumeun mae-u eomgyeokhan seonsaengnim cheoreom 느껴질 ttaega issseubnida: “Ani, geureoke hamyeon andwae. Geureoke-do andwae. Geugeot-do andwae. Geurigo daeche wae geureoke baraboni?” Sasil geugeon janjanddae-mun-i anira jogeumssik chimmuk-euro seumyeodeuneun o-ryu reul bangjihaneun boghojangchi-imnida. Dareun eoneo-eseoneun program-ui uimi-ga mogeunghage bakkwieodo moreugo jinagalsu issseubnida. Kotlin-eseoneun geoui modeun susa hyeong byeonhwan-eul myeongsi-jeok euro hamnida — jeuk, naega mwo-reul wonhaneunji-reul jigeop sseuneun geot-ibnida.

Yesanghae boseyo: halin-eul peosenteu-ro gyesanhago, geugeol Double ro jeojanghaetneunde, eoneu sungan eodinga-eseo “sil-suro” Int ro bakkumyeon so-su bu-bun-i sarajyeo beoribnida. Eoneo-ga ireol jadong-euro haejun다면, “halin-i gakkeum isanghae” gat-eun beogeureul myeot ju dongan ango sallado, eoneu sungan-eul jabgi jeonkkajin moreul su issseubnida. Kotlin-eun .toInt() reul sseuge haeseo, ma치 ireoke mutneun geot gatseubnida: “Jeongmal so-su-reul beoril geoya? Jinjjaro? Jeongmal jeongmal?”

I gyuchik-eun so-su-man-ui iyagiga animnida. Kotlin-eun uimi-sang anjeonhan gyeongu-eseodo Int → Double cheoreom “myeongsi-jeok anin hwakjang” eul johahaji anhseubnida. Geuraeseo “magic” dae신, gandan-hago ilgigi swiun methodeu-deuri issseubnida: toDouble(), toFloat(), toInt(), geurigo munja-ui segye-eseoneun Char ↔ su-ui yeongyeoldo issseubnida.

2. Basic number conversions

x.toInt() cheoreom boineun ho-chul-eul bomyeon, “Kotlin-i mwon-ga haetguna”라기boda “naega Kotlin-ege guchejeok-in jag-eob-eul butaekhanda”라고 saenggakhaneun geosi yuyonghamnida. Ige jung-yohan seupgwan-imnida: naega haeya hal dongjak-eul mal-lo jeonguihaji anh-eumyeon, hu-e naegen (geurigo mento-eseo-do) wae gyeol-gwa-ga “heulleojyeobeoryeotneunji” seolmyeonghagi eoryeowojibnida.

Are-neun gibon byeonhwan-ui uimi-reul meorissok-e daeumyeon jo-eun gandanhan pyo-ibnida:

Conversion Example What happens Where data loss can happen
Int → Double
5.toDouble()
jeongsu-ga so-su-ro bakkwiego, 값은 geudaero yujidoem daebubun eopseum
Int → Float
5.toFloat()
jeongsu-ga so-su-ro bakkwiejiman Float ga deo deol jeongmilham gakkeum iss-eum (keun su-eseo)
Double → Int
3.99.toInt()
so-su bu-bun-i beoryeojim (banollim anham!) so-su-ga iss-eumyeon hangsang
Double → Float
1e50.toFloat()
Infinity ga doegeona keun ogok-i saenggil su iss-eum iss-eum
Float → Double
1.5f.toDouble()
jeongmil-do-ga “bokgu” doeji anhjiman hyeong-i Double lo bakkwim i-jeon-e imi data-ga sonshil doeeosseul su iss-eum

Jigeum-eun biteu-na memori gujo-ro deureogaji angetsseubnida (geugeon dareun juje-imnida). Hajiman silje-yong gyeollon-eun gandanhamnida: hyeong keugi-ga jageojineun banghyang-ui byeonhwan (ye: Double → Int, Double → Float) eun — geoui hangsang 잠재적으로 wiheomhapnida.

Kodeu-ro hwaginhaebopsida.

fun main() {
    val x = 10
    val d = x.toDouble()

    println("x = $x")     // x = 10
    println("d = $d")     // d = 10.0
}

Yeogin jeonbu gwaenchansseubnida: Int → Double neun 값을 yujihago, danji “so-su bu-bun-eul gajil su issneun” ganeungseong-eul deohamnida.

Geureom ije data-ga sonshil doeneun yesireul bopsida:

fun main() {
    val price = 199.99
    val asInt = price.toInt()

    println("price = $price")   // price = 199.99
    println("asInt = $asInt")   // asInt = 199
}

Majimak-euro dasi han beon: toInt() neun banollim i anira, jeongmal로 so-su bu-bun-eul jal라 beorineun geot-imnida (siljelo 0-euro gakkaun jjog-euro i-dong). “Sa람답게 banollim” hage sipdamyeon, geugeon byeol-do-ui dan-gye-lo haeya hamnida (ije jeonui lecture-eseo baewotdeon round/floor/ceil reul gieokhagesse죠), geurigo geu daeum-e hyeong-eul byeonhwanhamnida.

3. Mixing types and subtle loss of meaning

Jageun yeonseup program-eul sseul ttaen hyeong byeonhwan-i deurmun il cheoreom 느껴jil su issseubnida. Hajiman “jin짜” gyesan (pyeonggyun, peosenteu, hwakryul, don) i deureoganeun sungan, beogeu-ui ban-eun if 도, loop 도 anira jal못된 wichi-e jal못된 hyeong-eul sseun geot im-eul geumse i haegyeon하게 doemnida.

Mae우 jeonghyeong-han sseenario: pyeonggyun-eul 구하고 sipseubnida. Hap ( Int ) gwa gaesu ( Int ) ga issseubnida. Nanu-gi-reul Int / Int 로 haebeoimyeon, so-su bu-bun-i sarajyeo beoribnida. Geuraeseo sik-eui han jjok-man-i라도 myeongsi-jeok-euro Double lo neom-eogaya hamnida.

fun main() {
    val sum = 7
    val count = 2

    val avg1 = sum / count
    val avg2 = sum.toDouble() / count

    println("avg1 = $avg1")  // avg1 = 3
    println("avg2 = $avg2")  // avg2 = 3.5
}

Programmer saeng-gakbangsik-eul gileobeoseyo: uri-neun “Kotlin-eul 고치는” geosi anira gyesan gyuchik-eul jeong-ui hamnida. So-su-reul wonhamyeon so-su-ro mandeuseyo.

Dareun jaju naneun gyeong-u-neun Float 와 Double ui hon-yong-imnida. Kotlin-eun dareun du so-su hyeong-eul silsu-ro 섞eoss-eul ttae joh-ahaji anhseubnida. Daebubun Double eun gibon hyeong-euro seontaekhago, Float eun jeongmal geureon iyu-ga iss-eul ttae-man sseuneun geosi swipseubnida.

4. Char: one character and why it’s useful

Ije saeroun hyeong-euro neomeogabnida — Char hyeong-imnida. Kotlin-eseo Char neun dan hana-ui munja ibnida. Geurigo singeul quote ro sseubnida: 'A', '7', '?'. Char literal-eun singeul quote-reul sse고, teukbyeol munja-neun escape sequence 로 pyohyeonhamnida.

Wae jungyohal-kka-yo? 초보-ja-ga jaju hekalineun bu-bun-i 있기 ttaemun-imnida:

  • '7' — “7” munja (hyeong: Char)
  • "7" — 길이 1 ui munjayeol (hyeong: String)
  • 7 — su (hyeong: Int)

Igeon se ro dae-gi bbeonhan dareun jonjae-imnida. Gakkeumeun seoro byeonhwanhal su issjiman, Kotlin-eun jadong-euro haejugi anhseubnida. Sil수로 babohan il-eul haebeo리지 mal라고 (geureon il-eun nuguna hamnida).

Char neun munjayeol-eseodo jaju deungjanghamnida: munjayeol-eun munja-ui yeonseog-i go, indekseu-ro gae-byeol munja-reul gajigo ol su issseubnida.

Escape characters: '\n', '\t', and others

Munjayeol-eul baewotdamyeon, eotteon munja-deul-eun “geudaero” sseugi eoryeoul su issdaneun geos-eul allyeogo sipseubnida. Geuraeseo escape sequence-ga issseubnida: '\n' — 줄바꿈, '\t' — tab 등. I geo-deul-do Char e soksseubnida.

fun main() {
    val a = 'A'
    val tab = '\t'
    val nl = '\n'

    println("[$a]")            // [A]
    println("x${tab}y")        // x    y
    println("line1${nl}line2") // line1
                               // line2
}

Yeogiseo tab gwa nl eun “chul-lyeok 명령” 같은 geos-i anira, jeongmal로 munja im-eul gieokhaseyo.

5. Char and numbers: codes, toChar(), and digits

Ibeon bu-bun-eun dangsin-eul jogeum deo “computer shaman” cheoreom mandeul geos-imnida. A-idie-neun dan순합니다: munja-eun susa code-reul gajinda. JVM-eseo Char neun 16-bit Unicode munja-imnida. 즉, munja-reul su-ro 볼 수도 있고, ban대로 su-reul munja-ro bakkul 수도 있습니다 (ganeunghan beomwi an-e isseul ttae).

Kotlin-eseo munja-neun code sogseong-eul gajigo, geugeon munja-ui susa code (hyeong: Int) reul 줍니다. Geu ban대ha-neun yeonsan-eun su-eui toChar() ibnida.

fun main() {
    val ch: Char = 'A'
    val code: Int = ch.code
    val back: Char = code.toChar()

    println("ch = $ch")        // ch = A
    println("code = $code")    // code = 65
    println("back = $back")    // back = A
}

Igeon magi-cheoreom boijiman, sasil-eun danji seoro yeokbyeonhwan dwaeneun du gae-ui byeonhwan-imnida.

Gajang in-gi itneun silje yesi-neun suja-imnida. 키보드 입력-eun jaju 텍스트로 들어옵니다. Jeonche Int reul parsing 하지 않더라도, gakkeumeun 딱 한 자리 suja-reul munja-ro gajigo 와서, suja인지 확인하고, su-ro 바꿔야 할 때가 있습니다.

또한 code-reul sayonghamyeon “shift” 도 할 수 있습니다: 'A' + 1 → 'B', '0' + 7 → '7'. Kotlin-eseo ireon a-idie-neun munja-reul bigyo-hago su-cheoreom byeonhwanhaneun task-eseo jaju deungjanghamnida.

“Digit character” → number without magic

'7' eul su 7 로 bakkuneun geos-eun jeongmal gibon-ibnida. 초보-ja-neun jaju ireon sig-euro haeryeogo 합니다:

  • "7".toInt() — munjayeol-e daeheseo-neun doejiman, Char 에는 an doem
  • ('7').toInt() — andwae요. Char ga jadong-euro “digit value” 로 byeonhwan doeji anhseubnida
  • 7.toChar() — jeon혀 ban대 방향이며, '7' ga anira code 가 7 in munja (je-eo munja) reul 줍니다

Ol바른 bangbeob-eun ireoh습니다: munja ch ga 있고, geugeon '0'..'9' beomwi an-e 있다고 확신한다면, digit 값은 code-ui cha-ibnida: digit = ch.code - '0'.code

Meonjeo, jeongmal suja인지 확인해 bopsida.

fun main() {
    val ch = '7'

    val isDigit = ch >= '0' && ch <= '9'
    val digit = if (isDigit) ch.code - '0'.code else -1

    println("isDigit = $isDigit")  // isDigit = true
    println("digit = $digit")      // digit = 7
}

Yeogiseo -1 eun yesi-reul wihan “error signal” imnida: suja-ga 아니면, suja-ga 될 수 없는 값을 돌려주는 geot-ibnida. N중-e deo jeonggyohan error cheori bangbeob-eul 배우면 다르게 하겠지만, 지금은 이것으로 충분합니다.

Ireon seutail (munja bigyo, beomwi cheori, code로 byeonhwan) eun gidae ro uimi-reul wihan geosi anira, silje Kotlin kodeu-eseo, teuk히 algorithm task-eseo jaju boineun 패턴임을 gieokhaseyo.

6. Mini scenario: generating a coupon from letters and digits

Console mini app LuckyCoupon eul 만든다고 가정해 봅시다. 사용자에게 할인율(%)과 A7Q2 형식 (munja–suja–munja–suja) ui kupon code-reul 출력합니다. Loop-eun eopseubnida — bonjil-eul nolliji 않으려고 danji 네 번의 step만 사용합니다.

핵심 아이디어: random munja-reul 얻기 위해, random su 0..25 reul 뽑고, 'A' ui code-e 더한 뒤 Char 로 되돌립니다.

import kotlin.random.Random

fun main() {
    val letter1 = ('A'.code + Random.nextInt(0, 26)).toChar() // 'A'..'Z'
    val digit1  = ('0'.code + Random.nextInt(0, 10)).toChar() // '0'..'9'

    val letter2 = ('A'.code + Random.nextInt(0, 26)).toChar()
    val digit2  = ('0'.code + Random.nextInt(0, 10)).toChar()

    val code = "$letter1$digit1$letter2$digit2"
    println("Your coupon: $code") // example: A7Q2
}

Du 가지 poin-treul 주목하세요.

Cheot째: yeogin “byeonhwan magic” i eopseubnida. .code 와 toChar() reul tonghae code-reul myeongsi-jeok-euro 다룹니다. Kodeu-ga jogeum gilla jigejiman, uimi-ga 훨씬 명확해집니다: su → munja code, munja code → munja.

Dul째: nextInt(0, 26) 와 nextInt(0, 10) ui gyeonggye-reul jageun silsu 없이 jal sseossseubnida. Sanghan gyeonggye-neun poham doeji 않으므로, latin alphabet 26-ja-reul 딱 정확하게 덮습니다.

Discount and the place where the fractional part often disappears

Halin-eul Double 로 gyesan한다고 해봅시다 (예: “floated” random halin). 출력할 때는 퍼센트를 정수로 보여주고 싶습니다. 여기서 선택해야 합니다: so-su-reul 잘라낼지, 아니면 banollim할지. 지금은 차이를 보기 위해, 의도적으로 “so-su sonshil” 케이스를 보여주겠습니다.

fun main() {
    val discount = kotlin.random.Random.nextDouble() * 30.0  // 0.0..30.0
    val discountInt = discount.toInt()                       // fraction truncated

    println("discount = $discount")           // discount = 12.345678...
    println("discountInt = $discountInt%")    // discountInt = 12%
}

Banollim-eul “gyuchik daero” 하고 싶다면, 이제 별도의 단계로 처리해야 한다는 점을 알고 있습니다.

7. Cheat sheet diagram for conversions

Gakkeumeun gae-byeol methodeu-보다, gandanhan “route” reul meorissok-e du-neun geosi yuyonghamnida. Are-neun jageun flowchart 로, “so-su jal라내기” 와 “banollim” eul hekal리지 않게 도와주며, munja-ga code segye-eseo sall-a issdaneun geos-do gieok하게 해줍니다.

flowchart TD
    A["Value exists"] --> B{Number or character?}
    B -->|Number| C{Need a different numeric type?}
    C -->|Yes| D["Explicit: toDouble/toFloat/toInt"]
    C -->|No| E["Keep as-is"]
    D --> F{Converting from Double to Int?}
    F -->|Yes| G["Understand: fractional part will be lost"]
    F -->|No| H["Usually safer"]
    B -->|Char character| I["Take ch.code (Int)"]
    I --> J{Want a digit?}
    J -->|Yes| K["Check '0'..'9' and subtract '0'.code"]
    J -->|No| L["Convert numbers ↔ characters via toChar()"]

8. Common mistakes

Mistake 1: confusing '7', "7", and 7.
Ise geot-eun se 가지 other type-imnida: Char, String, Int. Suja-reul Char 로 jeojang하면, geugeon su 7 do 아니고 "7" munjayeol-do 아닙니다. Char 에게 munjayeol methodeu-reul sseuryeogo 하거나, Char ga jeolo “su-ga doel geot” irago 기대하는 geos-i hon란과 isanghan byeonhwan-ui jaju naneun weon-in-imnida.

Mistake 2: thinking toInt() rounds.
toInt() neun banollim-i anira so-su bu-bun-eul beoryeobnida. Igeon teukhi “discount 12.9% ga 13% doegesseji” 라고 생각했는데 12% ga na올 때 ma-eu nasseubnida. Kotlin-i jal못한 게 아닙니다: dangsin-i butaekhan geot-eul geudaero haessseubnida. Banollim suhak-i 필요하다면, meonjeo banollim-eul 하고, geu daeum Int 로 byeonhwan하세요.

Mistake 3: doing Double → Int “later somewhere,” without thinking about meaning.
Gakkeumeun “il단 Double 로 두고, 맨 끝에서 Int 로 바꾸지 뭐” 라고 씁니다. Igeon wiheomhapnida: error-ga nateul ttaen imi too late라서, eodi-eseo munje-ga sijakdoe-eossneunji 알기 어려울 수 있습니다. Dae신, himdeun gyeyak-eul du세요: eodi-eseo jeongmilhan gyesan ( Double ) eul jeojang하고, eodi-eseo jeongsu gyeolgwa ( Int ) ga jeongmal로 필요한지, geurigo byeonhwan-eul uimi-ga boineun wichi-eseo ha세요.

Mistake 4: converting a digit from Char to Int without range checking.
ch.code - '0'.code reul sseuneun geos-eun, ch ga jeongmal로 '0'..'9' beomwi an-e iss-eul ttae-man 올바릅니다. Man약 'A' ga 들어오면, 어떤 su (예: 17) ga 나와도 program-i an jukseubnida — 그냥 이상한 일을 하기 시작합니다. Geuraeseo meonjeo check, geu daeum byeonhwan-imnida.

Mistake 5: forgetting that Char is a Unicode character, not “a letter from the ASCII table.”
Yeonseup yesi-eseoneun 'A'..'Z' wa '0'..'9' reul pyeon-an-hage sseugo, ye측 가능하게 dongjakhamnida. Hajiman Char neun Kotlin-eseo Unicode-imyeo, “munja” neun latin-man issneun geosi 아니란 점을 gieokhaseyo. Geuraeseo “munja code” 와 guchejeok-in beomwi-ro saenggakhaneun geosi, “munja니까 +1하면 daeum munja” 라고 saenggakhaneun 것보다 더 정확합니다.

1
과제
Kotlin SELF, 레벨 6, 레슨 5
잠금
출입증 코드
출입증 코드
1
과제
Kotlin SELF, 레벨 6, 레슨 5
잠금
소수점 없는 평균
소수점 없는 평균
1
과제
Kotlin SELF, 레벨 6, 레슨 5
잠금
한 버튼
한 버튼
1
설문조사/퀴즈
Real numbers, 레벨 6, 레슨 5
사용 불가능
Real numbers
Real numbers
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION