//var修饰的变量可修改var a:Int=10println(a)
a =20println(a)//val修饰的常量不可修改
val b =10println(b)var c ="abc"println("你好"+c)println(s"你好,$c")/*
%s 字符串类型
%d 整形
%c 字符类型
*/printf("你好,我是%s,我今年%d岁了\n",c,a)/*
2代表一共显示2位,若数字位数超过2,则显示全部数字,若数字位数小于2,则前面会用空格补全
3代表一共显示3位小数,四舍五入
*/var height =1.9dvar name ="张三"println(f"$name%s is $height%2.3f 米")//三引号标识字符串,保持多行字符串的原格式输出
条件语句
// 条件语句
val i =10;if(i>5){println("max five")}elseif(i ==5){println("equal five")}else{println("min five")}// if单行表达式可以省略{}
val o =if(i ==10) i +1else i
val x =5
val y ={println("我是一个代码块")
x+5}//scala中的三目元算符
val age =16println(if(age <18)"未成年"else"成年")
循环语句
var num =0while(num <5){println(num)
num = num +1}println("--------")do{println(num)
num = num +1}while(num <5)println("--------")//从1到5循环5次var n =5for(m <-1to(n)){println(m)}//倒序循环for(i<-10to1by(-1)){println(i)}
或
for(i<-1to10 reverse){println(i)}println("--------")//从1到4循环4次for(m <-1 until (5)){println(m)}/*
循环中断
break必须和breakable配合使用,同时要导入import scala.util.control.Breaks._;
*/breakable(for(i <-1to(10) by (2)){if(i >=5){break;}println(i *100)})/*
for循环过滤
每个条件之间用分号分隔
*/
val q =10for(i:Int<-1toq;if i%2==0;if i>5){println(i)}
val q =10
val ints =for(i:Int<-1toq;if i %2==0;if i >5)yield i
for(a<-ints)println(a)//迭代器遍历
val iterator = ints.iterator
while(iterator.hasNext){println(iterator.next())}
循环练习
//三角形for(a <-1to(5)){for(b <-1toa){print("*")}println()}println("--------")for(a <-1to(5)){for(b <-1to6- a){print("*")}println()}println("--------")for(a <-1to(5)){for(c <-1 until (a)){print(" ")}for(b <-1to6- a){print("*")}println()}println("--------")
breakable {
val line =10for(a <-1to(line)){if(a ==1){for(a <-1to(line +1)){print("*")}println()}else{if(a == line){println("*")break();}print("*")for(c <-1to(10- a)){print(" ")}print("*")println()}}}println("--------")
breakable {
val line =10for(a <-1to(line)){if(a ==1){for(a <-1to(line +1)){print("*")}println()}else{if(a == line){for(e <-1toline)print(" ")println("*")break();}for(b <-1 until a){print(" ")}print("*")for(c <-1to(10- a)){print(" ")}print("*")println()}}}println("--------")//乘法表for(a <-1to9){for(b <-1toa){print(s"$a*$b="+ a * b +"\t")}println()}
数组和元组
//数组
val arr =newArray[String](3)arr(0)="hello"arr(1)="abc"arr(2)="java"println(arr.to)
val arr2 =Array("1","2","3")//从1到10(开区间),以2增长的数组
val arr3 =Array.range(1,10,2)for(a<-0until(arr3.length)){println(arr3(a))}//元组,最多22个元素//声明方式一
val tp =("hello",'a',32)println(tp._1)//迭代元组
tp.productIterator.foreach(w=>println(s"value=$w"))//声明方式二
val tuple =newTuple2[String,String]("hehe","haha")println(tuple._2)
def ox ="green"->36"
println(ox)