포스팅 OS : Mac

검색어 : 코틀린(Kotlin), 이터레이션(Iteration), For, In, Map, Collection


▶︎ 이전 포스팅 목록

2018/02/10 - [Android_Kotlin] - [Android Kotlin] 안드로이드 스튜디오(Andorid Studio)에 코틀린(Kotlin) 개발환경 셋팅

2018/03/14 - [Android_Kotlin] - [Android Kotlin] 텍스트뷰(TextView)와 버튼(Button)을 사용한 헬로 코틀린

2018/03/14 - [Android_Kotlin] - [Android Kotlin] 함수와 변수를 이용하여 에디트텍스트(EditText)에 입력한 값 중 큰 값 구하기

2018/03/15 - [Android_Kotlin] - [Android Kotlin] 문자열 템플릿(String Template) 사용법

2018/06/05 - [Android_Kotlin] - [Android Kotlin] 클래스, 프로퍼티, 커스텀 접근자 - 라디오 버튼(Radio Button)


코틀린에서의 이터레이션(Iteration)에 대해 알아보겠습니다.

코틀린에서의 이터레이션은 자바와 흡사합니다. 그중 while 루프는 자바와 동일하므로 이번 포스팅에 다루지 않습니다. while을 제외한 for, in, map, collection에 대해 예제로 사용법을 알아보겠습니다.


1. 레이아웃
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.kotlin_test.Main1Activity.ForInActivity">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="피즈버그 게임"
android:textSize="20dp"
android:textStyle="bold"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="10"
android:orientation="horizontal">
<RadioGroup
android:id="@+id/rdo_direction"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="7"
android:orientation="horizontal"
android:gravity="center">
<RadioButton
android:id="@+id/rbtn_increase"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="증가"
android:paddingRight="20dp"/>
<RadioButton
android:id="@+id/rbtn_decrease"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="감소" />
</RadioGroup>
<EditText
android:id="@+id/edt_step"
android:hint="스텝 입력"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="3"
android:background="@null"
android:gravity="center"/>
</LinearLayout>

<Button
android:id="@+id/btn_for1"
android:text="실행"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="20sp"/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="맵 이터레이션"
android:textSize="20dp"
android:textStyle="bold"/>
<Button
android:id="@+id/btn_for2"
android:text="실행"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="20sp"/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="컬렉션 이터레이션"
android:textSize="20dp"
android:textStyle="bold"/>
<Button
android:id="@+id/btn_for3"
android:text="실행"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="20sp"/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="컬렉션 이터레이션"
android:textSize="20dp"
android:textStyle="bold"/>
<EditText
android:id="@+id/edt_ins1"
android:hint="숫자 혹은 문자 입력"
android:layout_width="match_parent"
android:layout_height="50dp"
android:maxLength="1"
android:background="@null"
android:gravity="center"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="6"
android:orientation="horizontal">

<Button
android:id="@+id/btn_for4"
android:text="문자검사"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="2"
android:textSize="20sp"/>

<Button
android:id="@+id/btn_for5"
android:text="숫자검사"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="2"
android:textSize="20sp"/>

<Button
android:id="@+id/btn_for6"
android:text="When 사용"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="2"
android:textSize="20sp"/>

</LinearLayout>

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/txt_for_log"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="20sp"
android:gravity="center"/>
</ScrollView>
</LinearLayout>





2. 소스

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.kotlin_test.R
import kotlinx.android.synthetic.main.activity_for_in.*
import java.util.*

class ForInActivity : AppCompatActivity() {

var log = ""

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_for_in)

var increase = true

// Radio Button 리스너
rdo_direction.setOnCheckedChangeListener { radioGroup, i -> if(i == R.id.rbtn_increase) increase = true else increase = false }
// Radio Button 기본값 기정
rdo_direction.check(R.id.rbtn_increase)


// for ---------------------------------------------------------------------------------------------------------------------------
// 피즈버그 게임 실행 버튼
btn_for1.setOnClickListener {
log = ""
txt_for_log.setText("")

if(increase) {
// for 증가 (..)
if(edt_step.text.toString().equals("")) {
for (i in 1..100) {
log += fizzBuzz(i) + "\n"
}
} else {
val num = Integer.parseInt(edt_step.text.toString())

// step : 증가값 지
for (i in 1..100 step num) {
log += fizzBuzz(i) + "\n"
}
}

txt_for_log.setText(log)
} else {
// for 감소 (downTo)
if(edt_step.text.toString().equals("")) {
for (i in 100 downTo 1) {
log += fizzBuzz(i) + "\n"
}
} else {
val num = Integer.parseInt(edt_step.text.toString())

// for 감소 : downTo
for (i in 100 downTo 1 step num) {
log += fizzBuzz(i) + "\n"
}
}

txt_for_log.setText(log)
}
}

// 맵 이터레이션 실행 버튼
btn_for2.setOnClickListener {
log = ""
txt_for_log.setText("")

// 키에 대해 정렬하기 위해 TreeMap 사용
val binaryReps = TreeMap<Char, String>()

// 입력 - 맵에 값 셋팅
for (c in 'A'..'F') {
val binary = Integer.toBinaryString(c.toInt()) // 아스키(ASCII) 코드를 2진 표현으로 바꾼다.
binaryReps[c] = binary // java로 표현하면 binaryReps.put(c, binary)와 같다.
}

// 출력 - 맵 키(letter)와 값(binary)을 두 변수에 각각 대입한다.
for ((letter, binary) in binaryReps) {
log += ("$letter = $binary\n")
}

txt_for_log.setText(log)
}

// 컬렉션 이터레이션 실행 버튼
btn_for3.setOnClickListener {
log = ""
txt_for_log.setText("")

// 입력 - 컬렉션 인덱스(index)와 값(element)을 두 변수에 각각 대입한다.
var list = arrayListOf("10", "11", "1001")
for((index, element) in list.withIndex()) {
log += ("$index = $element\n")
}

txt_for_log.setText(log)
}



// in ---------------------------------------------------------------------------------------------------------------------------
// 문자검사 버튼
btn_for4.setOnClickListener {
log = ""
txt_for_log.setText("")

var str = edt_ins1.text.toString()

if(!str.equals("")) {
var c_arr: CharArray = str.toCharArray()

if (isLetter(c_arr[0])) {
txt_for_log.setText("문자 검사 : true")
} else {
txt_for_log.setText("문자 검사 : false")
}
}
}

// 숫자검사 버튼
btn_for5.setOnClickListener {
log = ""
txt_for_log.setText("")

var str = edt_ins1.text.toString()

if(!str.equals("")) {
var c_arr: CharArray = edt_ins1.text.toString().toCharArray()

if (isDigit(c_arr[0])) {
txt_for_log.setText("숫자 검사 : true")
} else {
txt_for_log.setText("숫자 검사 : false")
}
}
}

// WHEN사용 버튼
btn_for6.setOnClickListener {
log = ""
txt_for_log.setText("")

var str = edt_ins1.text.toString()

if(!str.equals("")) {
var c_arr: CharArray = edt_ins1.text.toString().toCharArray()

txt_for_log.setText(recognize(c_arr[0]))
}
}
}

// 피즈버즈 게임
fun fizzBuzz(i: Int) =
when {
i % 15 == 0 -> "FizzBuzz " // 15로 나눠서 떨어지면 FizzBuzz
i % 3 == 0 -> "Fizz " // 3으로 나눠서 떨어지면 Fizz
i % 5 == 0 -> "Buzz " // 5으로 나눠서 떨어지면 Buzz
else -> "$i "
}

// in을 사용해 값이 범위에 속하는지 검사하기 : 문자
fun isLetter(c: Char) = c in 'a'..'z' || c in 'A'..'Z'

// in을 사용해 값이 범위에 속하는지 검사하기 : 숫자
fun isDigit(c: Char) = c in '0'..'9'

// !in을 사용해 값이 범위에 속하지 않는지 검사하기
fun isNotLetter(c: Char) = c !in 'a'..'z' || c !in 'A'..'Z'

// when에서 in 사용하기
// 문자열에 국한되지 않고 비교가 가능한 클래스(java.lang.Comparable 인터페이스가 구현된 클래스)라면 그 클래스의 인스턴스 객체를 사용해 범위를 만들 수 있다.
fun recognize(c: Char) = when (c) {
in '0'..'9' -> "숫자"
in 'a'..'z', in 'A'..'Z' -> "문자"
else -> "I don't know…​"
}
}


3. 실행 결과




+ Recent posts