代码块
package com.example.yoho1807.test.demo
import android.annotation.SuppressLint
import java.text.SimpleDateFormat
import java.util.*
fun main() {
//todo 遍历 1-100
for (i in 1..100) {
println(i)
}
//todo 倒叙遍历使用标准库中定义的downTo()函数
for (i in 100 downTo 1) {
println(i)
}
//todo 想不使用1作为遍历的步长,可以使用step()函数:
for (i in 1..100 step 2) {
println(i)
}
//todo 集合排序 添加下标为2的int值
val list = mutableListOf(2, 1, 3, 5, 2, 7, 3)
list.add(2, 3)
//todo 正序
println(list.sorted())
// [1, 2, 2, 3, 3, 3, 5, 7]
//todo 倒叙
println(list.sortedDescending())
// [7, 5, 3, 3, 3, 2, 2, 1]
//todo 调用计算器方法qaq()
val add = qaq(4, 2, "+")
println(add)
//todo 获取当前时间
val date = Date()
val simpleDateFormat = SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒")
val time = simpleDateFormat.format(date)
println(time)
}
//简单的计算器 加减乘除
fun qaq(i: Int, j: Int, z: String): Int {
when (z) {
"+" -> return i + j
"-" -> return i - j
"*" -> return i * j
"/" -> return i / j
else -> return 0
}
}
for循环 遍历 1-100
输出就不展示了
for (i in 1..100) {
println(i)
}
倒叙遍历使用标准库中定义的downTo()函数
倒叙100-1
for (i in 100 downTo 1) {
println(i)
}
想不使用1作为遍历的步长,可以使用step()函数:
输出结果是 1.3.5…97.99
for (i in 1..100 step 2) {
println(i)
}
集合排序 添加下标为2的int值
val list = mutableListOf(2, 1, 3, 5, 2, 7, 3)
list.add(2, 3)
//todo 正序
println(list.sorted())
//输出 :[1, 2, 2, 3, 3, 3, 5, 7]
//todo 倒叙
println(list.sortedDescending())
//输出 : [7, 5, 3, 3, 3, 2, 2, 1]
获取当前时间
val date = Date()
val simpleDateFormat = SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒")
val time = simpleDateFormat.format(date)
println(time)
//输出 : 2021年01月07日14时07分02秒
简单的计算器 加减乘除
fun qaq(i: Int, j: Int, z: String): Int {
when (z) {
"+" -> return i + j
"-" -> return i - j
"*" -> return i * j
"/" -> return i / j
else -> return 0
}
}
调用计算器方法
val add = qaq(4, 2, "+")
println(add)
// 输出 : 6
这篇博客介绍了Kotlin编程中的for循环、倒序遍历、自定义步长遍历,以及集合排序。展示了如何在列表中添加元素并进行正序和倒叙排列。此外,还讲解了如何获取当前日期和时间,并实现了一个简单的加减乘除计算器函数。
1423





