scala 快速入门开发二

三、scala中for使用

package org.zw.test

object ForCode {
  def main(args: Array[String]) {
    //		test();
//		test2();
		test3();
//		println(testmatch(2));
  }

  def test(): Unit = {
    //	  for(i <- 1.to(100)){
    //		  println(i)
    //	  }
    for (i <- 1 to 10) {
      println(i)
    }
  }

  //只有1-9 沒有10
  def test2() = {
    for (i <- 1 until 10) {
      println(i)
    }
  }

  //直接加入表達式在循环里面
  def test3() = {
    for (i <- 0 to 100 if (i % 2) == 1; if (i % 5) > 3) {
      println("I: " + i)
    }
  }

  //	switch
  def testmatch(n: Int) = {
    n match {
      case 1 => { println("111"); n; }
      //    没有	break;
      case 2 => println("2222"); n;
      case _ => println("other"); "test"; //default
    }
  }
}

四、map的使用

package org.zw.test

object MapCode {
  def main(args: Array[String]) {

    //	  _ 通配符  =>匿名函数   <- for便利符号

    // mutable
    // immutable
    var m1 = Map[String, Int](("a", 1), ("b", 2));

    println(m1("a"));
    //往map中加入元素
    m1 += ("c" -> 3);
    println(m1)
    //a 是一个元祖
    m1.foreach(a => {
      println(a + " " + a._1 + " " + a._2)
    });
    //遍历map
//    m1.keys.foreach(b => println(m1(b)));
    //获取到map 的键值
    m1.keys.foreach(b => print(b));
    println()
    m1.values.foreach(a => print(a));
    println()
    println(m1)
  }
}


猜你喜欢

转载自blog.csdn.net/u010982856/article/details/52869771
今日推荐