利用模式匹配编写一个 swaparr ArrayInt 函数交换数组中前两个元素的位置。所用数组如下:难度指数★★★Array1 2 3 4 5程序运行结果如下:新数组中的元素为:21345用Scala写完整代码object怎么运行
object SwapArray { def main(args: Array[String]): Unit = { val arr = Array(1, 2, 3, 4, 5) swap(arr) println("新数组中的元素为:" + arr.mkString(",")) }
def swap(arr: Array[Int]): Unit = { arr match { case Array(a, b, rest@_*) => arr(0) = b arr(1) = a case _ => // do nothing } } }
// 运行结果: // 新数组中的元素为:2,1,3,4,5
原文地址: https://www.cveoy.top/t/topic/cZYJ 著作权归作者所有。请勿转载和采集!