import java.util.Random
// mutableListOf: 수정가능한 Lits
fun main() {
var random = Random()
var list = mutableListOf<Int>()
while(list.size < 6){
val randomNumber = random.nextInt(45) + 1
if(list.contains(randomNumber)){
continue
}
list.add(randomNumber)
}
print(list)
}
2. Set 활용하여 1 ~ 45 까지 번호 가져오기
import java.util.Random
// mutableSetOf를 이용하여 중복검사 로직을 하지 않고 바로 랜덤값을 넣어준다.
fun main() {
var random = Random()
var numberSet = mutableSetOf<Int>()
while(numberSet.size < 6){
val randomNumber = random.nextInt(45) + 1
numberSet.add(randomNumber)
}
print(numberSet)
}
3. List에 미리 45번까지의 데이터를 가지고 있다가 앞에서 6번째까지 데이터 가져오기
import java.util.Random
/**
* You can edit, run, and share this code.
* play.kotlinlang.org
*/
fun main() {
var random = Random()
var list = mutableListOf<Int>().apply{
for(i in 1 .. 45){
this.add(i)
}
}
list.shuffle()
print(list.subList(0,6))
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// EditText타입 변수에 각 EditText의 값을 가져온다.
val heightEditText: EditText = findViewById(R.id.heightEditText)
val weightEditText = findViewById<EditText>(R.id.weightEditText)
val resultButton = findViewById<Button>(R.id.resultButton)
}
}
에러 해결 alt + enter
버튼 클릭 이벤트 처리
// 버튼 클릭 이벤트 처리
resultButton.setOnClickListener {
// 로그 찍기
Log.d("MainActivity","ResultButton 이 클릭되었습니다.")
// 비어있는 값일 경우 경고창을 띄워주고 종료
if (heightEditText.text.isEmpty() || weightEditText.text.isEmpty()) {
Toast.makeText(this,"빈 값이 있습니다.", Toast.LENGTH_SHORT).show()
/*버튼 클릭 함수를 나온다.*/
return@setOnClickListener
}
// Int형으로 변환하여 변수에 값 저장
val height:Int = heightEditText.text.toString().toInt()
val weight:Int = weightEditText.text.toString().toInt()
Log.d("MainActivity", "height : $height, weight : $weight")
// MainActivity에서 ResultActivity 호출 Intent(새로운 액티비티 전 화면, 새로 호출할 화면)
val intent = Intent(this, ResultActivity::class.java)
startActivity(intent)
}
입력후 결과를 보여줄 Activity를 생성(Result Activity.kt, activity_result.xml)
코틀린 소스파일과 layout화면 을 함께 생성한다.
아래와 같은 에러가 나온다면 manifests에 등록을 해주어야 한다.
Unable to find explicit activity class {com.example.aoppart2chapter01/com.example.aoppart2chapter01.ResultActivity}; have you declared this activity in your AndroidManifest.xml?
계속해서 코드 추가
ResultActivity.kt
package com.example.aoppart2chapter01
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlin.math.pow
class ResultActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_result)
// Intent로 전송한 데이터를 받는 방법 (intent 이전 화면에서의 Intent 변수명)
val height = intent.getIntExtra("height",0)
val weight = intent.getIntExtra("weight",0)
Log.d("ResultActivity", "height: $height, weight: $weight")
// pow: 제곱근 함수 사용
val bmi = weight / (height / 100.0).pow(2.0)
val resultText = when {
bmi >= 35.0 -> "고도 비만"
bmi >= 30.0 -> "중정도 비만"
bmi >= 25.0 -> "경도 비만"
bmi >= 23.0 -> "과체중"
bmi >= 18.0 -> "정상체중"
else -> "저체중"
}
// 레이아웃에 정의해둔 요소와 연결시킨다.
val resultValueTextView = findViewById<TextView>(R.id.bmiResultTextView)
val resultStringTextView = findViewById<TextView>(R.id.resultTextView)
// 연결된 요소에 데이터 입력
resultValueTextView.text = bmi.toString()
resultStringTextView.text = resultText
}
}
fun sum(a: Int, b: Int): Int {
return a + b;
}
fun sum(a: Int, b: Int) = a + b
fun max(a: Int, b: Int) = if (a > b) a else b
변수(var), 상수(val) 선언
val a: Int = 1
val b = 2
val c = 3.14
val d: String
// d = "d의 초기값이 없으면 null이 될 수 있는데, kotlin은 null이 가능한 타입과 아닌 타입이 있기때문에
에러가 발생할 수 있다."
d = "필수로 있어야 하는 구문"
val e: String?
var d: String = "첫번째 초기화"
e = "두 번째 초기화"
For 반복문
for (i in 1..5){
println(i)
}
// 1 2 3 4 5
for (i in 6 downTo 0 step 2) {
println(i)
}
// 6 4 2 0
for (i in 1..5 step 3) {
println(i)
}
// 1 4
val numberList = listOf(100, 200, 300)
for (number in numberList){
println(number)
}
// 100 200 300
While 반복문
var x = 5
while (x > 0) {
println(x)
x--
}
// 5 4 3 2 1
x = 0
while (x > 0) {
println(x)
x--
}
// 출력 없음
var y = 0
do {
print(y)
y--
} while (y > 0)
// 0
IF 문
var max: Int
if (a > b) {
max = a
} else {
max = b
}
// As expression
val max = if (a > b) {
print("Choose a")
a
} else {
print("Choose b")
b
}
when 문(자바에 switch문 대신)
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
when (x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}
when (x) {
in 1..10 -> print("x는 1부터 10범위 안에 있음")
!in 1..20 -> print("x는 1부터 20범위 안에 없음")
else -> print("otherwiese")
}
when (x) {
is Int -> print("x는 인트형")
else -> print("x는 인트형이 아님")
}
Null Safe
Integer a = 100;
//null 허용
val b: Int? =100
//null 허용X
val c: Int = 100
a = null;
// 중략
a.sum(); // NullPointException이 날 수도 있음
// null safe 한 코드를 구성해야함
if (a != null) {
a.sum();
}
b?.sum() // null일 경우 실행하지 않음
c.sum() // 애초에 nullsafe함
val person = Person().apply{
firstName = "Fast"
lastName = "Campus"
}
Also 함수
람다 입력값을 받고 다시 리턴(객체의 유효성 확인, 디버깅 용도로 사용)
Random.nextInt(100).also {
print("getRandomInt() generated value $it")
}
Random.nextInt(100).also { value ->
print("getRandomInt() generated value $value")
}
Let 함수
null이 아닌 객체에서 사용
val number: Int?
// null이 아닐 경우 sum 사용 null일 경우 빈값으로 치환
val sumNumberStr = number?.let {
"${sum(10, it)}"
}.orEmpty()
With 함수
person에 있는 함수를 사용
val person = Person()
with(person) {
work()
sleep()
println(age)
}
Run 함수
객체 구성과 결과계산이 한번에 실행될 때 유용
val result = service.run {
port = 8080
query()
}
Data Class
데이터를 저장하는 목적으로 만든 클래스
// 생성자, getter, setter 등 모두 만들어 진다.
data class JavaObject(var s: String)
Lambda expression
// 자바방식
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
...
}
})
// kotlin 방식
button.setOnClickListener { v ->
}
lateinit
변수를 나중에 초기화 하는 방법
var nullableNumber: Int? = null
lateinit var lateinitNumber: Int
// 추후 초기화 하는 코드
lateinintNumber = 10
// 사용할 때
nullableNumber?.add()
lateinitNumber.add()