scala (1) for 循環

scala if  else 判斷java

(1)在scala中末尾不須要添加 分號 做爲語句的終結符。  val  name = "Leo"數組

  (2)  在 scala 中 if else 是有返回值的,返回值是最後一條語句。if(num > 10)"Li" else 2函數

  (3) 由於 if 和 else 是有值的 因此能夠直接將 if 和 else 的結果複製給某個變量  val  name = if(num > 10)"Li" else 2    由於返回值類型不同  因此推斷其公共父類型是 anyspa

  (4) 在 scala中 不管是方法仍是函數 以及條件判斷等 只要是有返回值的 都不須要加 return 關鍵字  val name = if (num > 20) "zs" else "lisi"scala

(5)若是 沒有else 的語句塊,則對else 結果推斷爲 unit 即 沒有else 返回值  會返回  ()  相似於  java 的 voidcode

if else 練習 :blog

import scala.io.StdIn // import scala.util.control.Breaks._ object BaseDemo { def main(args: Array[String]): Unit = { val userName = StdIn.readLine("please write your username" + "\n") val passWord = StdIn.readLine("please write your password" + "\n") if(userName.equals("admin") && passWord.equals("root")){ println("welcome somebody") }else{ println("get out") } } }

 

scala  for 循環字符串

(1)使用 to 會產生一個接二連三的區間範圍  狀態:左右都是閉區間get

object BaseDemo { def main(args: Array[String]): Unit = { val a = 1 to 10 println( a) for ( i <- 1 to 10){ print(i) } } } // Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) //12345678910

(2)使用until 會產生一個連續不間斷的區間  狀態:左閉右開it

object BaseDemo { def main(args: Array[String]): Unit = { for(i <- 0 until 10){ print(i) } } } // 0123456789

(3)for循環遍歷字符串

object BaseDemo { def main(args: Array[String]): Unit = { for(i<- "pwefjpwfpwkf[w"){ // println(i)
        print(i + ",") } } } // p,w,e,f,j,p,w,f,p,w,k,f,[,w,

(4)多重for循環遍歷  九九乘法表

def main(args: Array[String]): Unit = { for(x <- 1 to 9 ; y <- 1 to 9){ if (y == 9){ println(x + "*" + y + "=" + x * y ) }else print(x + "*" + y + "=" + x * y + " \t ") } } } /* 1*1=1 1*2=2 1*3=3 1*4=4 1*5=5 1*6=6 1*7=7 1*8=8 1*9=9 ... 9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81 */

(5)帶 if 守衛的 for 循環

object BaseDemo { def main(args: Array[String]): Unit = { for(i <- 1 to 10 ){ if (i % 2 == 0)  print (i + ",")  else () } } }
// 2,4,6,8,10,

(6)推導式 for 循環  yield 會拿到每個元素,而後對其進行 i * 3 的操做

object BaseDemo { def main(args: Array[String]): Unit = { val arr = for( i <- 1 to 5 ) yield i *  3
    for(j <- arr){ print(j + ",") } } }
// 3,6,9,12,15,

(7)for 循環遍歷數組 Array

object BaseDemo { def main(args: Array[String]): Unit = { val arr = Array(1,"hello","a") for(a <- arr){ print(a + ",") } } } // 1,hello,a,

(8) 中斷 for循環 

import scala.util.control.Breaks._ object BaseDemo { def main(args: Array[String]): Unit = { breakable({ for (i <- 0 to 10) { print (i + ",") if (i >= 5) { break() } } }) } } // 0,1,2,3,4,5,

(9)if 守衛 中斷 for循環

object BaseDemo { def main(args: Array[String]): Unit = { for(i <- 0 to 10){ if(i <= 5){ print(i + ",") } } } } // 0,1,2,3,4,5,
相關文章
相關標籤/搜索