ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [코틀린 강의 정리]_loop section
    etc/코틀린_안드로이드 2021. 9. 28. 16:28

    >>18 .kotlin Loopsfundamental  :

    loop is fundamental in programming cause we control whole program by  using loop to make different situation by same code by itteration of code and end  predetermined under conditions using as like if or conditon statment

     

    :. if 문과 조건문을 조합한 반복문은 프로그램을 우리가 원하는 방향으로 만드는데 중요한 요소이다.

     

    반복문은 크게 3 가지 while, do while , for 문으로 소개를 한다.

     

    simple way

    1. while

     

    if the experssions evaluate to true code in the body block excuted  

    :. while 안에 조건이 참이면 while 이 동작을 한다

    import android.util.Log

    //log  사용시 라이브러리 임포트를 해준다.

     

    var x = 10

    //변수 x 를 선언후 10으로 초기화

     

    while(x > 0 )

    {

       Log.i(" x = ","$x")

       x--

    }

     

     !!!!! log 간단 정리         질문! :   println 과 뭔차이 ?    >나중에 찾아본다.

    로그는 print문만 사용해본 개발자로서 생소 할 수 있지만 간단한 출력문이라고 이해를 하고 넘어가자 일단. 

     

    로그의 종류는 다음과 같다.

     

     사용한 로그문은 안드로이드 스튜디오 하단  logcat  / info 에서 확인이 가능하다.

    static int Log.i (String tag, String msg [, Throwable tr]) i 는 information 의 약자로 일반 정보를 표시할 때 사용됩니다.

     

    - static int Log.d (String tag, String msg [, Throwable tr]) d 는 debug 의 약자로 debug 용 로그입니다.

     

    - static int Log.e (String tag, String msg [, Throwable tr]) e 는 error 의 약자로 error 용 로그입니다.

    보통 exception 이 발생하거나 Error 가 발생할 경우 system이 이녀석을 활용합니다

     

    -  static int Log.w (String tag, String msg [, Throwable tr]) w 는 warning 의 약자로 경고를 표시합니다.

    보통 exception 이 발생했을 때 자주 쓰입니다. ( error 와 구분. )

     

    -  static int Log.v (String tag, String msg [, Throwable tr]) v 는 verbose 의 약자로,  개발중에만 나타내는 용도의 로그입니다.

    참고 링크:

    https://hashcode.co.kr/questions/1007/%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9C%EC%97%90%EC%84%9C-logvlogdlogilogwloge-%EA%B0%81%EA%B0%81-%EC%96%B8%EC%A0%9C-%EC%93%B0%EB%82%98%EC%9A%94

     

     

    아무튼

     

    Log.i("thi is final value","$x")

     

    다음과 같은 코드 추가 후 x 값 확인을 하자.  

     

     

    while 반복문에 조건을 넣는다면 다음과 같다.

    while(x > 0 || 1 < x )

     

     

    2. do while

    do-while의 경우에는 최소 한 번은 실행해야할 때 사용합니다. 이게 무슨 말이냐?

    코드 부터 보자.

    ex code)

    // while

           while(false){

               println("while loops")

           }

     

    // do-while

           do{

               println("do-while loops")

           }while(false)

     

    >>output : “do- while loops”

    do 문을 무조건 사용을 하고 while 문을 실행을 한다. 쉽게 생각 해서 일반 while 문 위에 실행할 코드를 한번 적어 준것과 같은 효과를 준다.        cf, 많은 교수님들이 코드의 복잡성이 증가 하며 이해 하기 어려울 수있다며 추천 하는 방식은 아니다.

     

    응용 : 사용자 입력을 받고 while 문 돌리기 



     

    3. for

    코틀린은 자바 베이스의  언어라고 알고 있는데 실제 문법은 파이썬에서 보았던것과 유사하다.

     

    코드 부터 보자.

    ex code)

    val list = 1..10

    for(i in list)

    {

       Log.i("loop","for current value is $i")

    }

    >>list 값 설정을 1..10 이라 보는데 이는 1~10 까지 값을 순차적으로 갖는 것과 같다.

     

     

    *Rangers 사용은 다음과 같이 

     

    val rangeOfNumbers = 1..4 // = 1,2,3,4

    val rangeOfNumber = listOf(1,2,3,4)



    당연하게도 break 와 continue 문이 있다.

     

    -break문은 break 를 적어준 곳에서 해당 조건문 블록과 그 밖의 반복문 자체를 탈출한다.

    ex code)

    /// using break

    var countdown = 10

    while (countdown > 0)

    {

       if(countdown ==5)

       {

           break

       }

       Log.i("countdown ","$countdown")

       countdown--

    }




    /// using continue

    var countup = 0

    while (countup < 10)

    {

       countup++

       if(countup >5)

       {

           continue

       }

       Log.i("inside ","$countup")

    }

    Log.i("ot","$countup")


     

     

    -continue문은 해당 조건문 블록을 탈출하여 아래 명령문은 실행하지 않고, 다음 반복문 실행절차를 수행한다.   >  smae as python

     

     

    var countup = 0

    while (countup < 10)

    {

       countup++

       Log.i("inside0 ","$countup")

       if(countup >5)

       {

           continue

       }

       Log.i("inside1 ","$countup")

       Log.i("inside2 ","$countup")

    }

     

    Log.i("ot","$countup")

     

    부연 설명  >>> continue문 하단부는 무시하고 ,반복문 상단 블록으로 올라와 상단부만 출려되는 모습이다.





    chpt 19. For loop in  kotlin  

    다양한 방식으로 For 문의 반복 횟수를 정하거나 출력하는 값을 선택할 수 있다.

     

    var variable: String

    for (index in 1..5)

    {

       Log.i("value of index  is ","$index ")

    }

    var variable: String

    for (index in 1..5)

    {

       Log.i("value of index  is ","$index ")

    }

    for(index in "Hello Academy")

    {

       Log.i("index in string ","$index")

    }

    for(index in 100 downTo 90)

    {

       Log.i("log using downto ","$index")

    }

     

    for(index in 1 until 10)

    {

       Log.i("log using until",index.toString())

    }

     

    for(index in 1 until 100 step 3)

    {

       Log.i("log using until step 3",index.toString())

    }

     코드의 종료 시점을 주의 해서 보자.

     

     

     

    chpt 21. kotlin Statments and conditions

    if를 이용한 조건

     

    코드 ex)

    import android.widget.TextView

    val textView: TextView = findViewById(R.id.textView)
    // R(resource file) 에 있는 textview 라는 아이디 를 가져와 우리가 지정한 textView 라는 value 에 저장한다.
    val x = 10
    if( x>9 ) textView.setText("100 is bigger")

     

    axtivity_main xml에  다음과 같이 id 를 추가 해야 한다.

     

     //응용 

     

    var mike = 19
    var john = 17
    if (mike>john)
    {
    textView.setText("mike is order than john")
    } else
    {
    textView.setText("mike is not order than john")
    }

     

     

    자바의 switch 문과 같은 조건문도 있다. 

     

    code ex)

    when(mike){
    16 ->textView.setText("ho")
    17 ->textView.setText("ly")
    18 ->textView.setText("mol")
    19 ->textView.setText("mike is 19")
    20 ->textView.setText("abab")
    else -> textView.setText("mike could be over than 20 ")
    }

     

     

    정리:

     

    코틀린에서는 for ,while, do while, if,else when() 등과 같은 반복문과 조건문들을 사용한다. 

    log.i() 를 사용해서 출력값을 확인하거나, 다음과 같은 코드를 작성하여 앱에서 결과를 확인 하는것이 가능하다.

     

    val textView: TextView = findViewById(R.id.textView)
    if( x>9 ) textView.setText("100 is bigger")

     

    'etc > 코틀린_안드로이드' 카테고리의 다른 글

    Kotlin if vs when 성능 비교 ?  (0) 2022.09.29
    Kotlin Nullable  (0) 2022.09.29
    Deep in to Kotlin(feat .android)  (0) 2022.09.27
    코틀린 자바 장단점 비교, Kotlin vs Java  (1) 2022.09.25
    uppercase(),버전 확인 문제  (0) 2021.09.27
Designed by Tistory.