Android Application

KorTlin while 문

작성자 임베디드코리아 작성일23-08-27 20:28 조회1,826회 댓글0건

첨부파일

----------------------------------------------------------------------------------------
    MainActivity..kt
----------------------------------------------------------------------------------------
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //텍스트뷰 초기화
        var textView : TextView = findViewById(R.id.textView);

        var a1: Int = 0
        var b1: Int = 4

        while(a1<b1){ // a<b 가 성립할때 반복문 실행
            a1++ //while문이 무한 루프가 돌지 않도록 a값 증가
            textView.append("$a1,  ") //1 2 3 출력
            if(a1 == 3) break //무한이 돌지 않도록 break문 추가
        }

        textView.append("\n");

        var a = 10
        while(a > 5){
            textView.append("$a  ")
            a--
        }

        textView.append("\n");

        val value = 2

        val result = when (value) {
            1 -> "첫번쨰"
            2 -> "두번쨰"
            3 -> "세번쨰"
            4 -> "네번째"
            else -> "기타"
        }
        textView.append("$result \n") // "두번째"
        textView.append("-------------------------- \n")
        textView.append("[while true 무한 루프 \n 카운트 수행 및 \nbreak 반복문 탈출 실시]\n");
        textView.append("\n");
        //int형 초기 변수 선언 실시
        var int_data = 1;

        //while true 무한 루프 반복문 실행
        textView.append("[program start]\n");

        while(true){
            if(int_data == 5){
                textView.append("["+int_data+"]\n");
                break //while 무한루프 탈출
            }
            textView.append("[$int_data]  ");
            int_data ++ //int 값 증가 실시
        }

        textView.append("[program end]\n");
    }
}

----------------------------------------------------------------------------------------
    activity_main.xml
----------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>