天天看點

Groovy快速入門-5-switch分支和循環語句

上一篇快速過了一下操作運算符和if else判斷語句,分支語句中,還有一個switch沒有介紹。

1.switch分支

來一個成績劃分的例子

package com.anthony.demo


// switch分支語句
def int score = 99

switch(score) {
	case {0 < score && score < 60}:
		println("不及格")
		break
	case {60 < score && score <= 70}:
		println("及格")
		break
	case {70 < score && score <= 80}:
		println("良")
		break
	case {80 < score && score <= 90}:
		println("優秀")
		break
	case {90 < score && score <= 100}:
		println("A+")
		break
	default:
		println("良")
}



           

2.for循環

這個完全和Java中的for循環一樣,就是我們平時寫冒泡排序這個for循環。

package com.anthony.test

// for loop
for(int i=1; i<=5; i++) {
	println i
}
           

就是列印出1到5

3.for in 循環

這種循環在Java中叫增強型for循環,或者for each,和這個差不多。關鍵字in感覺是從python那邊學習過來的。

package com.anthony.test

// for in loop
for(a in 1..5) {
	println a
}
           

運作結果是一樣,1到5列印出來

一般使用for in 後面跟着一個list,或者map對象

package com.anthony.test

// for in loop
for(x in [2, 3, 4, 5]) {
	println x
}
           

來看一個map的例子

package com.anthony.test

// for in map
def map = ["name":"Groovy", "sbuject":"Automation"]
for(e in map) {
	print e.key + ":"
	println e.value
}
           

輸出

name:Groovy
sbuject:Automation
           

4.upto關鍵字

還有upto關鍵字也可以實作這樣效果

package com.anthony.test

// upto
1.upto(5) { 
	println "$it"
}
           

it就是表示循環中變量,這種固定寫成it寫法,以後在介紹閉包之後就會習慣,閉包中經常這樣寫。

5.times關鍵字

和upto類似效果,times關鍵字是預設從0開始。

package com.anthony.test

// times
5.times { println "$it" }
           

列印結果是0 1 2 3 4, 這個預設從0開始,注意下。

6.step關鍵字

就是從一個數開始,step表示步長,直接看下面例子來了解文法

package com.anthony.test

// step
1.step(10, 2) { println "$it" }
           

運作輸出是 1 3 5 7 9, 不包含10,你把1改成0,輸出0 2 4 6 8,沒有10.

7.while循環

很簡單的一個例子

package com.anthony.test

// while loop
int i = 1
while (i < 5) {
	println i
	i++
}