当前位置:网站首页>Kotlin---- control statement
Kotlin---- control statement
2022-06-21 08:13:00 【Dialogue】
1、 Conditional branch
(1)、 Simple branches –if…else
kotlin in if…else Statement has a return value , Be similar to Java The trinomial operation in
// Pass in two values a and b , Show large values in TextView Control nameTextView.text=if(a>b) a else b
(2)、 Multiple branches
A: characteristic
kotlin There is no switch/case ,
- Use when/else replace
- when/else There are also return values
- After executing a node, the loop is terminated
- The criteria in the branch can be constant / Variable / expression ——Java Medium switch/case in case Nodes can only be constants
- To make sure everything is judged , Usually cannot omit else
B: Basic use
var count:Int = 0 btn_when_simple.setOnClickListener {
tv_answer.text = when (count) { 0 -> " The value is 0"
1 -> " The value is 1"
else -> " Other values "
}
count = (count+1) % 3
}C: through
java in switch/case Each constant condition needs to be listed when penetration is required , but kotlin Can simplify ——
- Multiple conditions are written directly on one line , Use ”,“
- Interval if the condition is continuous , You can specify the interval range
- If the condition is a continuous number , And it needs to be judged that it is not within the range , Then use
btn_when_region.setOnClickListener { tv_answer.text = when (count) {
1,3,5,7,9 -> " The value is 13579 One of them "
in 13..19 -> " The value is 13 To 19 One of them "
!in 6..10 -> " Value no longer 6 To 10 Between " else -> " Other values "
}
count = (count+1) % 20
}D、 Take the expression as the branching condition
kotlin in adopt is Keywords are used to judge A Is it B Example —— , Equate to Java Medium A instance B .
var countType:Number; btn_when_instance.setOnClickListener {
count = (count+1) % 3 countType = when (count) {
0 -> count.toLong();
1 -> count.toDouble() else -> count.toFloat()
}
tv_answer.text = when (countType) { is Long -> "Long type "
is Double -> "Double type " else -> " Other types "
}
}2、 Loop processing
(1)、 Traversal cycle
namely for-in 、forEach、 The use of iterators
(2)、 condition loop
Execute when a condition is met / End cycle .
A: Use keywords
So , Added multiple keywords :until、setp、downTo
// Traverse 11 To 66 Value between ,until A left closed and right open interval is declared —— It doesn't contain 66, contain 11 for (i in 11 until 66) {
...
}
// Traverse 23-89 Value between , Step by step to 4—— Every time +4.23..89 Declare an interval that is both left and right closed
for (i in 23..89 step 4) {
...
}
// Traversal in reverse order from 50 To 7
for (i in 50 downTo 7) {
...
}B: Use while、do/while
Due to the limited keywords , The effect that can be achieved is limited , therefore , More complex logic can be used while or do/while Realization
btn_repeat_begin.setOnClickListener { var poem:String=""
var i:Int = 0
while (i < poemArray.size) { if (i%2 ==0) {
poem = "$poem${poemArray[i]}\n"
} else {
poem = "$poem${poemArray[i]}\n"
}
i++
}
poem = "${poem} The poem consists of ${i} sentence " tv_poem_content.text = poem
}btn_repeat_end.setOnClickListener { var poem:String=""
var i:Int = 0 do {
if (i%2 ==0) {
poem = "$poem${poemArray[i]}\n"
} else {
poem = "$poem${poemArray[i]}\n"
}
i++
} while (i < poemArray.size)
poem = "${poem} The poem consists of ${i} sentence " tv_poem_content.text = poem
}(3)、 Break the loop
Use break—— Break the loop 、continue—— Skip this cycle , The basic usage is the same as Java,
in addition , When nested loops , You can also use @ Loop tag name Specify the loop to break .
btn_repeat_break.setOnClickListener { var i:Int = 0
var is_found = false
// [email protected] To label an outer loop , The name is outside [email protected] while (i < poemArray.size) {
var j:Int = 0
var item = poemArray[i]; while ( j < item.length) { if (item[j] == ' One ') { is_found = true
// The interrupt tag is named outside The cycle of [email protected]
}
j++
}
i++
}3、 Empty processing
(1)、 Validity judgment of string
Method for verifying empty string :
- isNullOrEmpty —— by null Or the length is 0 When to return to true.
- isNullOrBlank —— by null Or the length is 0 Or all the spaces , return true.
- isEmpty —— The length is 0 When to return to true, We must first judge the non - null
- isBlank —— The length is 0 Or all spaces return true, We must first judge the non - null
- isNotEmpty —— Longer than 0 When to return to true, We must first judge the non - null
- isNotBlank —— Longer than 0 And non space returns true, We must first judge the non - null
(2)、 Declare nullable variables
kotlin The default variable in is not empty , If you need to declare an nullable variable , Then a question mark is appended to the type ?
ar strCanNull:String?
(3)、 Operators for checking null values ——?、?:、!!
? Can be empty , If empty, return directly null
?: Indicates that once it is empty, the value after the colon is returned , Otherwise, it returns the normal value
!! Indicates that the assertion is not empty ( Discard non empty judgments ). however , If you make this assertion , But still null, Then null pointer will be reported .
var length_null:Int? btn_question_dot.setOnClickListener {
//strB Followed by one ”?“ It means that you can null, If null Then return directly null, here length_null The value of is null
length_null = strB?.length
tv_check_result.text = " Additional ? The length obtained when calling the object property is $length_null"
}btn_question_colon.setOnClickListener {
// If strB Not null, Return to normal strB.length; If strB by null, Then return to -1
length = strB?.length ?: -1
tv_check_result.text = " Use ?: The length obtained when calling the object property is $length"
}btn_exclamation_two.setOnClickListener {
strB = "ABCDE"
// Only onehundredpercent are certain that it is not null when , Only use !!, Otherwise, the null pointer will still be reported length = strB!!.length
tv_check_result.text = " Use !! The length of the attribute value obtained when asserting is $length"
}4、 Equality judgment
(1)、 Equal structure
- kotlin Use in == Judge whether two data are equal , Use != Judge whether it is not equal .
- kotlin Medium String It's the same way .Java Use in equals()
- kotlin When comparing strings in, the storage addresses in memory are no longer compared , Instead, compare the values of variables directly , This method is called Equal structure , That is, they look the same / Same appearance .
(2)、 Reference equivalence
If you need to determine whether the references are equal , That is to judge whether the memory addresses are consistent ,kotlin Use in =, If the judgment is inconsistent , Then use !
- For basic data types ( Including strings ), Structure equality is consistent with reference equality .
- adopt clone Even if the attribute value of the object is the same , But the reference address is inconsistent .
(3)、is and in
- is and !is —— Judge A Is it B Example , Such as : Object name is Class name
- in and !in —— Determine whether the array contains an element , Such as Variable name in Array name
边栏推荐
- 2021-07-28 STM32F103 configuration information
- Listing of flaunting shares on Shenzhen Stock Exchange: market value of 4.2 billion, 9-month revenue decreased by 21% year-on-year
- 2022-2028 global hydrogen internal combustion engine industry research and trend analysis report
- Illustration Google V8 14: bytecode (2): how does the interpreter interpret and execute bytecode?
- Journal (résumé en langue c)
- Interview duck interview brush question website system source code
- 2021-06-16 STM32F103 EXTI 中断识别 使用固件库
- MySQL filter query (start with a letter, start with a number, start without a number, and start without a letter)
- Ansa secondary development - external programs use socket to communicate with ansa
- Permission management
猜你喜欢

Solve the problem that Jenkins cannot save the configuration after upgrading

Showctf starter file contains series

Yyds dry goods inventory rapid establishment of CEPH cluster

测试入门——软件测试模型

使用Lua+Redis+OpenResty实现电商首页并发优化

2022-2028 global boom cylinder industry research and trend analysis report

2022-2028 global after sales spark plug industry research and trend analysis report

Linux Installation of Damon database /dm8 (with client tool installation full version)

showCTF Web入门题系列

There was a GC failure in the online go service. I was in a hurry
随机推荐
Permission management
Linux安装达梦数据库/DM8(附带客户端工具安装完整版)
(for line breaks) differences between gets and fgets, and between puts and fputs
图解 Google V8 # 16:V8是怎么通过内联缓存来提升函数执行效率的?
Le Code est correct, mais les données de la base de données ne sont pas affichées.
一元多项式的乘法与加法运算 (20 分)
Diary (C language summary)
2021-06-16 STM32F103 exti interrupt identification using firmware library
2021-06-17 STM32F103 USART serial port code using firmware library
Images, graphics and Applications (II)
1005 spell it right (20 points) (test point 3)
Send using queue mailbox
Global and Chinese market of horizontal drilling rigs 2022-2028: Research Report on technology, participants, trends, market size and share
Why is there no error in the code, but the data in the database cannot be displayed
图解 Google V8 # 15:隐藏类:如何在内存中快速查找对象属性?
Eureka's timedsupersortask class (periodic task with automatic interval adjustment)
Flutter returns to the black screen of the previous page
MySQL filter query (start with a letter, start with a number, start without a number, and start without a letter)
The market value of Jinshan office fell below 100 billion yuan: the shareholder Qiwen n-dimensional cash out exceeded 1.2 billion yuan
2022-2028 global section valve industry research and trend analysis report