티스토리 뷰

공부/ComposeCamp 2022

unit 2: 연습 Kotlin 기초

데자와 맛있다 2022. 11. 23. 01:07

제시된 문제를 코틀린으로 구현, 코틀린을 연습한다

 

1. 모바일 알림 문제

알림이 100개 미만이면 정확히 알림이 몇갠지 표기, 100개 넘으면 99+로 표기한다

fun main() {
    val morningNotification = 51
    val eveningNotification = 135

    printNotificationSummary(morningNotification)
    printNotificationSummary(eveningNotification)
}

fun printNotificationSummary(numberOfMessages: Int) {
    // Fill in the code.
}

위의 기본코드를 바탕으로 아래와 같은 결과가 출력되도록 하라

fun main() {
    val morningNotification = 51
    val eveningNotification = 135

    printNotificationSummary(morningNotification)
    printNotificationSummary(eveningNotification)
}

fun printNotificationSummary(numberOfMessages: Int) {
    if(numberOfMessages>99){
        println("Your phone is blowing up! You have 99+ notifications.")
    }else{
        println("You have $numberOfMessages notifications.")
    }
}

2. 영화 티켓 가격

12세 이하 어린이 티켓 값 15달러

13~60세 표준 티켓 30달러, 그러나 월요일엔 25달러로 세일

61세 이상 노인 티켓 20달러, 최대 연령 100세

-1값은 사용자가 연령 분류에 속하지 않는 연령을 입력하는 경우 유효하지 않은 가격을 나타낸다

fun main() {
    val child = 5
    val adult = 28
    val senior = 87

    val isMonday = true

    println("The movie ticket price for a person aged $child is  \$${ticketPrice(child, isMonday)}.")
    println("The movie ticket price for a person aged $adult is \$${ticketPrice(adult, isMonday)}.")
    println("The movie ticket price for a person aged $senior is \$${ticketPrice(senior, isMonday)}.")
}

fun ticketPrice(age: Int, isMonday: Boolean): Int {
    // Fill in the code.
}

위 코드를 바탕으로 아래같은 결과를 출력하라

fun main() {
    val child = 5
    val adult = 28
    val senior = 87

    val isMonday = true

    println("The movie ticket price for a person aged $child is  \$${ticketPrice(child, isMonday)}.")
    println("The movie ticket price for a person aged $adult is \$${ticketPrice(adult, isMonday)}.")
    println("The movie ticket price for a person aged $senior is \$${ticketPrice(senior, isMonday)}.")
}

fun ticketPrice(age: Int, isMonday: Boolean): Int {
    if(age<=12){
        return 15
    }else if(age<=60){
        if(isMonday){
            return 25
        }else{
            return 30
        }
    }else if(age<=100){
        return 20
    }else{
        return -1
    }
}

아래는 when을 if else대신 사용한것

fun main() {
    val child = 5
    val adult = 28
    val senior = 87

    val isMonday = true

    println("The movie ticket price for a person aged $child is  \$${ticketPrice(child, isMonday)}.")
    println("The movie ticket price for a person aged $adult is \$${ticketPrice(adult, isMonday)}.")
    println("The movie ticket price for a person aged $senior is \$${ticketPrice(senior, isMonday)}.")
}

fun ticketPrice(age: Int, isMonday: Boolean): Int {
    return when(age) {
        in 0..12 -> 15
        in 13..60 -> if (isMonday) 25 else 30
        in 61..100 -> 20
        else -> -1
    }
}

3. 온도 변환기

  • 섭씨에서 화씨로: F = 9/5(°C) + 32
  • 켈빈에서 섭씨로: °C = K - 273.15
  • 화씨에서 켈빈으로: K = 5/9(°F - 32) + 273.15
fun main() {
    // Fill in the code.
}

fun printFinalTemperature(
    initialMeasurement: Double,
    initialUnit: String,
    finalUnit: String,
    conversionFormula: (Double) -> Double
) {
    val finalMeasurement = String.format("%.2f", conversionFormula(initialMeasurement)) // two decimal places
    println("$initialMeasurement degrees $initialTemperature is $finalMeasurement degrees $finalTemperature.")
}

위 코드를 바탕으로 아래와 같은 결과가 출력되도록 하라, main에서 온도와 변환 수식의 인수를 전달해야 한다

fun main() {
	printFinalTemperature(27.0,"Celsius","Fahrenheit"){degree:Double->
       	9.0/5.0*degree+32
    }
    printFinalTemperature(350.0,"Kelvin","Celsius"){degree->
       	degree-273.15
    }
    printFinalTemperature(10.0,"Fahrenheit","Kelvin"){
       	5.0/9.0*(it-32)+273.15
    }
}

fun printFinalTemperature(
    initialMeasurement: Double,
    initialUnit: String,
    finalUnit: String,
    conversionFormula: (Double) -> Double
) {
    val finalMeasurement = String.format("%.2f", conversionFormula(initialMeasurement)) // two decimal places
    println("$initialMeasurement degrees $initialUnit is $finalMeasurement degrees $finalUnit.")
}

4. 노래 카탈로그

음악 플레이어 앱을 만든다고 가정하자 노래 구조를 나타내는 클래스 Song을 만들자

Song에는 아래와 같은 요소가 있다

  • 제목, 아티스트, 발표 연도, 재생 횟수의 속성
  • 노래가 인기 있는지 나타내는 속성. 재생 횟수가 1,000회 미만이면 인기가 없다고 간주합니다.
  • 다음 형식으로 노래 설명을 출력하는 메서드: '[제목]을 연주한 [아티스트이름], 출시연도는[발표연도]'
fun main() {
    val brunoSong = Song("We Don't Talk About Bruno", "Encanto Cast", 2022, 1_000_000)
    //_를 사용하면 큰 단위 수를 가독성 있게 작성하는게 가능함
    brunoSong.printDescription()
    println(brunoSong.isPopular)
}

class Song(
    val title:String,
    val artist:String,
    val year:Int,
    val playNum:Int
){
    val isPopular:Boolean
    	get()=playNum>=1000
    fun printDescription(){
        println("$title 을 연주한 $artist, 출시연도는 $year")
    }
}


5. 인터넷 프로필

fun main() {
    val amanda = Person("Amanda", 33, "play tennis", null)
    val atiqah = Person("Atiqah", 28, "climb", amanda)

    amanda.showProfile()
    atiqah.showProfile()
}

class Person(val name: String, val age: Int, val hobby: String?, val referrer: Person?) {
    fun showProfile() {
       // Fill in code
    }
}

위 코드를 바탕으로 아래와 같은 결과가 출력되게 하라

Name: Amanda
Age: 33
Likes to play tennis. Doesn't have a referrer.

Name: Atiqah
Age: 28
Likes to climb. Has a referrer named Amanda, who likes to play tennis.
fun main() {
    val amanda = Person("Amanda", 33, "play tennis", null)
    val atiqah = Person("Atiqah", 28, "climb", amanda)

    amanda.showProfile()
    atiqah.showProfile()
}

class Person(val name: String, val age: Int, val hobby: String?, val referrer: Person?) {
    fun showProfile() {
       println("Name: $name")
       println("Age: $age")
       if(hobby!=null){
           print("Likes to play $hobby. ")
       }
       if(referrer==null){
           print("Dosen't have a referrer.")
       }else{
           print("Has a referrer named ${referrer.name}")
           if(referrer.hobby!=null){
               print(", who likes to play ${referrer.hobby}.")
           }else{
               print(".")
           }
       }
       print("\n\n")
    }
}

6. 폴더블 스마트폰

기본 제공하는 코드에서 Phone클래스를 상속받는 FoldablePhone클래스를 만들어라

Foldablephone클래스는 아래를 포함한다

  • 휴대전화가 접혀 있는지 나타내는 속성
  • Phone 클래스와는 다른 switchOn() 함수 동작을 사용하여 휴대전화가 접혀 있지 않을 때만 화면이 켜지도록 합니다.
  • 접기 상태를 변경하는 메서드
open class Phone(var isScreenLightOn: Boolean = false){
    open fun switchOn() {
        isScreenLightOn = true
    }

    fun switchOff() {
        isScreenLightOn = false
    }

    fun checkPhoneScreenLight() {
        val phoneScreenLight = if(isScreenLightOn) "on" else "off"
        println("The phone screen's light is $phoneScreenLight.")
    }
}
class FoldablePhone(var isFolded:Boolean=true):Phone(){
    override fun switchOn(){
        if(isFolded==false){
            isScreenLightOn=true
        }
    }
    fun fold(){
        isFolded=true
    }
    fun unfold(){
        isFolded=false
    }
}
fun main() {
    val newFoldablePhone = FoldablePhone()

    newFoldablePhone.switchOn()
    newFoldablePhone.checkPhoneScreenLight()
    newFoldablePhone.unfold()
    newFoldablePhone.switchOn()
    newFoldablePhone.checkPhoneScreenLight()
}

7. 특별 경매

경매에서는 제일 높은 가격을 제시하는 입찰자가 상품 가격을 결정함

이 특별 경매는 입찰자가 아무도 없을때 최소 가격에 경매 회사에 물건이 팔린다

fun main() {
    val winningBid = Bid(5000, "Private Collector")

    println("Item A is sold at ${auctionPrice(winningBid, 2000)}.")
    println("Item B is sold at ${auctionPrice(null, 3000)}.")
}

class Bid(val amount: Int, val bidder: String)

fun auctionPrice(bid: Bid?, minimumPrice: Int): Int {
   // Fill in the code.
}

이 초기 코드를 이용해 아래같은 출력이 나오도록 해라

fun main() {
    val winningBid = Bid(5000, "Private Collector")

    println("Item A is sold at ${auctionPrice(winningBid, 2000)}.")
    println("Item B is sold at ${auctionPrice(null, 3000)}.")
}

class Bid(val amount: Int, val bidder: String)

fun auctionPrice(bid: Bid?, minimumPrice: Int): Int {
   if(bid==null){
       return minimumPrice
   }else{
       return bid.amount
   }
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함