1. 程式人生 > >Kotlin學習筆記-----流程控制

Kotlin學習筆記-----流程控制

不同 枚舉 並且 但是 端點 這樣的 基本 if條件 var

條件控制

if條件判斷

if的使用和java裏面一樣

// Java中的if
int score = 90;
if (score >= 90 && score <= 100) {
  System.out.println("優秀");
} else if (score >= 80 && score <= 89) {
  System.out.println("良好");
} else if (score >= 60 && score <= 79) {
  System.out.println("及格");
} else if
(score >= 0 && score <= 59) { System.out.println("不及格"); }
// Kotlin中的if
var score = 100;
if (score >= 90 && score <= 100) {
  System.out.println("優秀");
} else if (score >= 80 && score <= 89) {
  System.out.println("良好");
} else if (score >= 60 && score <= 79) {
  System.out.println(
"及格"); } else if (score >= 0 && score <= 59) { System.out.println("不及格"); }

但是如果有自己的特性

// 假設求兩個數的最大值
// java代碼
int a = 3;
int b = 4;
int max = 0;
if(a > b) {
    max = a;
} else {
    max = b;
}

但是在kotlin中, 可以進行優化

var a = 3
var b = 4
var max = 0
max = if(a > b) {
    a
} else {
    b
}
// 只不過寫習慣java後,這樣的形式看起來不習慣

另外, kotlin中可以通過in 來表示某個變量的範圍, 能夠代替java中繁瑣的 &&來表示 一個變量的範圍

var score = 100
//  score in 0..59 表示的就是 0 <= score <= 59
// in 表示範圍時, 肯定會包含兩個端點的值, 也就是包含0 和 59 
// 如果想要用in來表示不包含0和59, 如: 0 < score < 59
// 那麽就要調整範圍到 1~58, 也就是  score in 1..58
// 使用in後, 代碼可以表示如下形式
if (score in 0..59) {
  print("不及格")
} else if (score in 60..79) {
  print("及格")
} else if (score in 80..89) {
  print("良好")
} else if (score in 90..100) {
  print("優秀")
}

when表達式

when表達式和java中的switch類似, 但是java中的switch無法表示一個範圍, 而when可以和in來結合使用, 表示一個範圍

// 基本格式
// 並且不同於java中的switch只能表示 byte short int char String 枚舉等類型, 
// kotlin中的when可以表示很多類型, 比如boolean
var number = true
when (score) {
  true -> {     
    print("hello")
  }
  false -> print("world") // ->後面的大括號, 如果不寫, 那麽默認執行最近的一行代碼
  
}

// 上面那個if寫的根據不同分數, 做不同輸出的代碼, 如果使用when來做
var score = 100
when(score) {
  in 0..59 -> print("不及格")
  in 60..79 -> print("及格")
  in 80..89 -> print("良好")
  in 90..100 -> print("優秀")
  else -> print("信息有誤")     // 效果和if中的else, switch中的default一樣
}

同樣, 判斷兩個數最大值可以用when表示為:

val a = 3
val b = 4
val max = when(a > b) {     // 這裏能夠看到, switch中是不支持a > b這種寫法的, 而when中可以 
  true -> a
  false -> b
}
print(max)

Kotlin學習筆記-----流程控制