标签:style blog color java 使用 io for ar
import scala.collection.mutable.ArrayBuffer; object HelloWorld { def main(args: Array[String]) { //实现一个可变的数组(数组缓冲),以下两种方式等价 val mutableArr = ArrayBuffer[Int](); val mutableArr2 = new ArrayBuffer[Int]; mutableArr += 1; //用+=在尾端添加元素 mutableArr +=(1, 2, 3, 4, 5) //在尾端添加多个元素,以括号括起来 mutableArr ++= Array(8, 9, 10) //你可以使用++=操作符追加任何集合 mutableArr.trimEnd(7) //移除最后7个元素 println("length=" + mutableArr.length) println("size=" + mutableArr.size) print("元素="); for (elem <- mutableArr) { print(elem + " , ") } } }
object HelloWorld { def main(args: Array[String]) { val a = Array(2, 3, 5, 6); val result = for (elem <- a) yield elem * 2 result.copyToArray(a) for (elem <- a) { print(elem + ",") //output:4,6,10,12, } } }
//对元素值是偶数的进行翻倍操作,并舍弃掉值是奇数的元素 val b = a.filter(_ % 2 == 0).map(_ * 2); for (elem <- b) { print(elem + ",") }
import scala.collection.mutable.ArrayBuffer object HelloWorld { def main(args: Array[String]) { //移除除第一个负数之外的所有负数 val a = ArrayBuffer(1, -2, 3, 5, -4, -5) var first = true //首先收集需要保留的下标,返回的结果是一个vector集合 val indexs = for (i <- 0 until a.length if first || a(i) >= 0) yield { if (a(i) < 0) first = false; i } print(indexs) //output:Vector(0, 1, 2, 3) //然后将元素移动到该去的位置,并截断尾端 for (j <- 0 until indexs.length) { a(j) = a(indexs(j)) } println() a.trimEnd(a.length - indexs.length) print(a) } }
object HelloWorld { def main(args: Array[String]) { val matrix = Array.ofDim[Double](3, 4) //构造一个三行四列的二维数组 matrix(0)(0) = 56 //访问第一个元素 val triangle = new Array[Array[Int]](10) //创建一个十行的数组,每一行都是一个Int型的Array for (i <- 0 until (triangle.length)) { triangle(i) = new Array[Int](i + 1) //将每一行实例化成(i+1)列的二维数组 } //打印数组 for (i <- 0 until (triangle.length)) { for (j <- 0 until (triangle(i).length)) { print(triangle(i)(j) + ",") } println() } } }
标签:style blog color java 使用 io for ar
原文地址:http://blog.csdn.net/shijiebei2009/article/details/38614357