# Scala多维数组

## 多维数组语法

``````var arrayName = Array.ofDim[ArrayType](NoOfRows, NoOfColumns) or
var arrayName = Array(Array(element...), Array(element...), ...)``````

## 使用ofDim的Scala多维数组示例

``````class ArrayExample{
var arr = Array.ofDim[Int](2, 2)  		 // Creating multidimensional array
arr(1)(0) = 15                     		// Assigning value
def show(){
for(i<- 0 to 1){             		  // Traversing elements by using loop
for(j<- 0 to 1){
print(" "+arr(i)(j))
}
println()
}
println("Third Element = "+ arr(1)(1))        // Accessing elements by using index
}
}

object MainObject{
def main(args:Array[String]){
var a = new ArrayExample()
a.show()
}
}``````

``````0 0
15 0
Third Element = 0``````

## 通过使用数组数组来实现Scala多维数组

``````class ArrayExample{
var arr = Array(Array(1, 2, 3, 4, 5), Array(6, 7, 8, 9, 10))   // Creating multidimensional array
def show(){
for(i<- 0 to 1){               // Traversing elements using loop
for(j<- 0 to 4){
print(" "+arr(i)(j))
}
println()
}
}
}

object MainObject{
def main(args:Array[String]){
var a = new ArrayExample()
a.show()
}
}``````

``````1 2 3 4 5
6 7 8 9 10``````

## 两个矩阵的Scala加法示例

``````class ArrayExample{
var arr1 = Array(Array(1, 2, 3, 4, 5), Array(6, 7, 8, 9, 10))   // Creating multidimensional array
var arr2 = Array(Array(1, 2, 3, 4, 5), Array(6, 7, 8, 9, 10))
var arr3 = Array.ofDim[Int](2, 5)
def show(){
for(i<- 0 to 1){               // Traversing elements using loop
for(j<- 0 to 4){
arr3(i)(j) = arr1(i)(j)+arr2(i)(j)
print(" "+arr3(i)(j))
}
println()
}
}
}

object MainObject{
def main(args:Array[String]){
var a = new ArrayExample()
a.show()
}
}``````

``````2 4 6 8 10
12 14 16 18 20``````

• 回顶