1.Scala—For循环
for (i:Int<-1 to(10)){
print(i+ ".Hello World")
}
for (i<- Range(1,10)){
println(i+".hello world")
}
for (i <-1 until 10){
println(i+"hello world")
<1> 嵌套For循环
for (i:Int <-1 to 3){
for (j:Int<-1 to 3){
println("i="+i+" "+"j="+j)
}
}
for (i<-1 to 3; j<-1 to 3){
println("i="+i+" "+"j="+j)
}
for (i<-1 until(3);j<-1 until(3)){
println("i="+i+" "+"j="+j)
}
}
<2> 任务—打印九九乘法表(二种方法)
//任务:打印九九乘法表
for (i <- 1 to 9) {
for (j <- 1 to i) {
print(s"$j × $i=${i * j} \t")
}
println()
}
for (i<-1 to 9;j<-1 to i){
print(s"$j × $i=${i * j}\t")
if (i==j) {
println()
}
}
2.集合–循环遍历
//集合遍历
for (i <- Array(12,34,58)){
println(i)
}
for (i<-List(12,34,85)){
println(i)
}
for (i<-Set(12,34,58)){
println(i)
}
<1> 循环引入变量
for{i<-1 to 10;j=10-i} {
println("i= "+i+", j ="+j)
}
}
<2> 循环返回值
// 循环返回值
val b=for(i<-1 to 10) yield i * i
println("b="+b)
3.循环守卫—删除
for (i <- 1 to 10) {
if (i != 5) {
println(i)
}
for (i<- 1 to 10 if i !=5){
println(i)
}
<1>循环步长
for (i<-(1 to 10).by(2)){
println(i)
}
for (i<-13 to 30 by(3)) {
println(i)
}
for (i<-30 to 10 by(-2)){
println(i)
}
for (i<-1.0 to 10.0 by(0.8)){
println(i)
}
}
<2> 任务:用*打印正三角形 And 倒三角形(菱形)
for (i <- 1 to 5) {
val stars = 2 * i - 1
val spaces=5-i
println(" "* spaces+"*" * stars)
}
for (i<-1 to 9; stars=2*i-1;spaces=9-i)
println(" "*spaces+"*"*stars)
for (i<-9 to 1 by(-1);stars=2*i-1;spaces=9-i)
println(" "*spaces+"*"*stars)
4.While循环与Do-While循环
<1>(While)循环
// while循环,能使用for就使用for while必须要在外面定义变量
var a:Int=10
while (a>=1){
println("this is a while loop:"+a)
a-=1
}
<2> (Do- While)循环
var b=2
do{
println("while loop:"+b)
b-=1
}while (b>0)
5.抛出异常处理
<1> try与catch的使用
try{
for (i<-1 to 5) {
if (i == 3)
throw new RuntimeException
println(i)
}
}catch {
case e:Exception=>
}
<2> Breaks类的Break方法
// 2.使用Scala中的breaks类的break方法,实现异常的抛出和捕捉
Breaks.breakable(
for (i<-1 until 5){
if (i==3)
Breaks.break()
println(i)
}
)
println("循环外")
Breaks.breakable(
for (i<-1 to 5){
if (i==3) {
Breaks.break()
println(i)
}
}
)
|