알고리즘/백준

[백준] 9498 : 시험 성적 - 코틀린(Kotlin)

Junuuu 2022. 10. 25. 00:01
반응형

https://www.acmicpc.net/problem/9498

 

9498번: 시험 성적

시험 점수를 입력받아 90 ~ 100점은 A, 80 ~ 89점은 B, 70 ~ 79점은 C, 60 ~ 69점은 D, 나머지 점수는 F를 출력하는 프로그램을 작성하시오.

www.acmicpc.net

 

문제 해석

다른 언어라면 if-else를 활용하겠지만 코틀린에는 when을 활용하고자 합니다.

 

 

코드

import java.io.IOException

fun main() {
    val score = readLine() ?: throw IOException()
    val grade = getGrade(score.toInt())
    print(grade)
}

fun getGrade(score: Int): Char = when {
    score >= 90 -> 'A'
    score >= 80 -> 'B'
    score >= 70 -> 'C'
    score >= 60 -> 'D'
    else -> 'F'
}

 

다른 분들의 코드를 보고 배운 점

import java.io.IOException

fun main() {
    val score = readLine() ?: throw IOException()
    val grade = getGrade(score.toInt())
    print(grade)
}

fun getGrade(score: Int): Char = when(score) {
    in 90..100 -> 'A'
    in 80.. 90 -> 'B'
    in 70..80 -> 'C'
    in 60..70 -> 'D'
    else -> 'F'
}

in을 활용하여 사용할 수도 있습니다.