[Android 14 및 Kotlin 개발 완전 정복하기] 2일차 - 가위 바위 보 및 코틀린 기초
2일차! 부족한 개념은 Do it! 책을 활용했습니당. 코틀린 공식 문서가 굉장히 잘 되어있네요... 그치만 영어는 시러
몇 가지 부분은 건너뛰었습니당
Int 데이터 유형
Type | Size (bits) | Min value | Max value |
Byte | 8 | -128 | 127 |
Short | 16 | -32768 | 32767 |
Int | 32 | -2,147,483,648 (-231) | 2,147,483,647 (231 - 1) |
Long | 64 | -9,223,372,036,854,775,808 (-263) | 9,223,372,036,854,775,807 (263 - 1) |
Kotlin에서는 변수를 선언하는 두 가지 방법으로 val과 var이 있다.
- val : value의 줄임말로, 불변하는 값. 초깃값을 할당하면 재할당 할 수 없다.
- var : variable의 줄임말로 변하는 값. 초깃값을 할당하고 나서도 재할당 할 수 있다.
변수명 뒤에는 콜론(:)을 추가해 타입을 명시할 수 있으며, 타입을 명시하지 않아도 자동으로 Int로 저장된다. 이를 타입 추론이라고 한다. 만약 Int 범위가 넘어간다면 자동으로 Long으로 저장된다.
큰 숫자를 사용할 예정으로 Long을 쓰고 싶다면 L을 표기한다. 만약 Byte 또는 Short를 사용하고 싶다면 콜론 기호(:)를 통해 명시적으로 선언한다.
val one = 1 // Int
val threeBillion = 3000000000 // Long
val oneLong = 1L // Long
val oneByte: Byte = 1
Hello World 실행
온라인에서 코틀린을 실행시킬 수 있는 사이트
부호 없는 정수
Type | Size (bits) | Min value | Max value |
UByte | 8 | 0 | 255 |
UShort | 16 | 0 | 65,535 |
UInt | 32 | 0 | 4,294,967,295 (232 - 1) |
ULong | 64 | 0 | 18,446,744,073,709,551,615 (264 - 1) |
-128 ~ 127 대신 0~255를 사용한다. 1이 아닌 0부터 시작하고 양수 방향으로만 범위가 커진다.
대입하는 값 끝에 u또는 U를 붙여줘야 한다. 대문자, 소문자는 관계없다.
val b: UByte = 1u // UByte, expected type provided
val s: UShort = 1u // UShort, expected type provided
val l: ULong = 1u // ULong, expected type provided
val a1 = 42u // UInt: no expected type provided, constant fits in UInt
val a2 = 0xFFFF_FFFF_FFFFu // ULong: no expected type provided, constant doesn't fit in UInt
val a = 1UL // ULong, even though no expected type provided and the constant fits into UInt
정수의 전체 bit범위를 양수로 사용하고 싶을 때 부호없는 정수를 사용한다.
Booleans true, false, 부정
오직 두가지 값 true 또는 false를 가진다. Boolean?은 true, false, null 세 가지 값 중 하나를 가질 수 있다.
또한 세 개의 내장된 연산자를 가진다.
- ||
- &&
- !
Char, 유니코드 및 백슬래시 이스케이프 문자
하나의 문자만 저장 가능하며 작은 따옴표(')로 감싸서 표현한다.
유니코드를 표현하려면, \u를 붙이고 뒤에 유니코드 숫자만 붙인다.
println('\uFF00')
문자열
일련의 문자, 즉 단어나 문단들 같은 긴 문자 같은 것들을 저장할 수 있다. 큰따옴표(")로 감싸서 표현한다. 문자열(String)의 요소들은 문자(Char)들이며, s[i]와 같은 인덱싱 연산을 통해 접근할 수 있다. 또한, for (c in str) 같은 for문을 사용해 이 문자들을 순회(iterate)할 수 있다.
한 번 문자열을 초기화하면, 그 값을 바꾸거나 새 값을 할당할 수 없다. 문자열을 변형하는 모든 연산은 새로운 String 객체로 결과를 반환하며, 원래 문자열은 그대로 유지된다.
val str = "abcd"
// Creates and prints a new String object
println(str.uppercase())
// ABCD
// The original string remains the same
println(str)
// abcd
ReadIn 및 toInt를 사용하여 문자열을 정수 변수로 변환
readln() 함수를 사용하여 표준 입력으로부터 데이터를 읽는다. 이때 전체 줄을 문자열로 읽는다. 만약 다른 자료형으로 변환하고 싶으면 .toInt(), .toLong(), .toDouble(), .toFloat(), 또는 .toBoolean()와 같은 함수를 이용한다. 즉 .toInt()를 사용해서 Integer을 만들 수 있다. 이는 String을 파싱하여 Integer 숫자로 결과를 반환한다.
val age = readln().toInt()
.toInt(), .toDouble() 같은 형 변환 함수는, 입력된 문자열이 해당 자료형에 맞는 올바른 값일 거라고 가정하고 동작한다. 따라서서 "hello"처럼 숫자가 아닌 문자열을 변환하려고 하면 에러(예외)가 발생한다.
Else if 및 in 키워드
if (age in 18..39){...}
if (age >= 18 && age < 40){...}
in은 범위 지정 연산자로, 두 조건식은 같은 의미이다.
가위 바위 보
컴퓨터의 선택 받기
package com.example.rockpaperscissors
fun main(){
var computerChoice = ""
var playerChoice = ""
println("Rock, Paper or Scissors? Enter your choice!")
playerChoice = readln()
val randomNumber = (1..3).random()
if (randomNumber == 1) computerChoice = "Rock"
else if (randomNumber == 2) computerChoice = "Paper"
else computerChoice = "Scissors"
println(computerChoice)
}
1부터 3까지의 숫자 중 .random() 함수를 이용하여 숫자 하나를 무작위로 선정하여 변수 randomNumber에 저장한다.
승자 찾기
when문을 이용한다. when 키워드 다음의 소괄호()에 넣은 데이터가 조건이 되고 이 값에 따라 -> 오른쪽에 있는 구문을 실행한다. 또는 데이터를 명시하지 않고 조건만 명시할 수도 있다. 표현식으로도 사용할 수 있는데, 즉 when 문의 실행 결과를 반환할 수 있다. when문을 표현식으로 사용할 때는 else문을 생략할 수 없다.
val winner = when {
playerChoice == computerChoice -> "Tie"
playerChoice == "Rock" && computerChoice == "Scissors" -> "Player"
playerChoice == "Paper" && computerChoice == "Rock" -> "Player"
playerChoice == "Scissors" && computerChoice == "Paper" -> "Player"
else -> "Computer"
}
승자 표시
if (winner == "Tie") {
println("It's a tie")
}
else {
println(winner + " won!")
}
if (winner == "Tie") {
println("It's a tie")
}
else {
println("$winner won!")
}
String 타입의 데이터에 변숫값이나 어떤 연산식의 결괏값을 포함해야 할 때는 $ 기호를 이용한다. 이를 문자열 템플릿이라고 한다.
카운터와 함께 While 루프
fun main() {
var count = 0
while (count < 3) {
println("Count is $count")
count++
}
}
사용자 입력과 함께 While 루프
fun main() {
var userInput = readln()
while (userInput == "1") {
println("While loop executed")
userInput = readln()
}
println("Loop is done!")
}
퀴즈7: 코딩 연습 - 가위바위보 게임에서 플레이어 입력 유효성 검사
package com.example.rockpaperscissors
fun main(){
var computerChoice = ""
var playerChoice = ""
println("Rock, Paper or Scissors? Enter your choice!")
playerChoice = readln().lowercase()
while(playerChoice != "rock" && playerChoice != "paper" && playerChoice != "scissors"){
println("Rock, Paper or Scissors? Enter your choice!")
playerChoice = readln().lowercase()
}
val randomNumber = (1..3).random()
when (randomNumber) {
1 -> {
computerChoice = "Rock"
}
2 -> {
computerChoice = "Paper"
}
3 -> {
computerChoice = "Scissors"
}
}
println(computerChoice)
computerChoice = computerChoice.lowercase()
val winner = when {
playerChoice == computerChoice -> "Tie"
playerChoice == "rock" && computerChoice == "scissors" -> "Player"
playerChoice == "paper" && computerChoice == "rock" -> "Player"
playerChoice == "scissors" && computerChoice == "paper" -> "Player"
else -> "Computer"
}
if (winner == "Tie") {
println("It's a tie")
}
else {
println("$winner won!")
}
}
- 플레이어가 가위, 바위, 보만 입력하도록 강제
- 대소문자 구분을 없앰 -> rock, Rock, ROCK, rOCk 모두 바위로 처리
println(computerChoice) // Rock
computerChoice.lowercase()
println(computerChoice) // Rock
computerChoice = computerChoice.lowercase()
println(computerChoice) // rock
요약
https://tutorials.eu/exploring-basic-kotlin-syntax-and-structure-day-2-android-14-masterclass/
Exploring Basic Kotlin Syntax - Day 2 Android 14 Masterclass
Welcome to Day 2 of our Android 14 Masterclass, where we dive into the Basic Kotlin Syntax and Structure. Embark on this coding journey!
tutorials.eu