1.Scala while循环
只要判断条件成立,while 循环将一直运行对应代码块。例如,在下一个13 号的周五到来之前,下面的代码将按照一天一次的频率打印抱怨的信息:
import java.util.Calendar def isFridayThirteen(cal: Calendar): Boolean = { val dayOfWeek = cal.get(Calendar.DAY_OF_WEEK) val dayOfMonth = cal.get(Calendar.DAY_OF_MONTH) // Scala将最后一个表达式的结果值作为该方法的返回结果 (dayOfWeek == Calendar.FRIDAY) && (dayOfMonth == 13) } while (!isFridayThirteen(Calendar.getInstance())) { println("Today isn't Friday the 13th. Lame.") // sleep for a day Thread.sleep(86400000) }
2.Scala do-while循环
与while 循环相似,只要条件表达式返回true,do-while 循环语句就会执行代码。也就是说,执行完代码块后,do-while 语句便会检查条件是否为真。为了能计数十次,我们可以编写如下代码:
var count = 0 do { count += 1 println(count) } while (count < 10)