還記得初中的時候剛學編程,老師講到for循環(huán),布置的作業(yè)是打印九九乘法表。那么多年一轉眼就過去了,學習新語言就來打印一個有中國特色的九九乘法表吧。
上代碼:
fun main(args : Array<String>){
multiplicationTable()
}
fun multiplication(a: Int, b: Int) = a * b //Kotlin新特性!?。『啙嵜髁?!
fun multiplicationTable(){
for(i in 0..9){
if(i==0){
//打印第一行
for(i in 0..9){
if(i==0)
print("*\t")
else
print("$i\t")
}
println()
} else {
print("$i\t") //打印第一列
for(j in 1..i){
//打印內(nèi)容
print(multiplication(i,j).toString()+"\t")
}
println() //換行
}
}
}
為了學習Kotlin的特性,特意將乘法獨立出來寫(雖然只有一行=。=)
輸出結果:
* 1 2 3 4 5 6 7 8 9
1 1
2 2 4
3 3 6 9
4 4 8 12 16
5 5 10 15 20 25
6 6 12 18 24 30 36
7 7 14 21 28 35 42 49
8 8 16 24 32 40 48 56 64
9 9 18 27 36 45 54 63 72 81