scala代码示例

Scala supports the array data structure. An array is a fixed size data structure that stores elements of the same data type. The index of first element of an array is zero and the last element is the total number of elements minus one.

Scala支持数组数据结构。 数组是固定大小的数据结构,用于存储相同数据类型的元素。 数组的第一个元素的索引为零,最后一个元素的元素总数为一。

Scala数组声明 (Scala Array Declaration)

The syntax for declaring an array variable is

声明数组变量的语法是

var arrayname = new Array[datatype](size)

var indicates variable and arrayname is the name of the array, new is the keyword, datatype indicates the type of data such as integer, string and size is the number of elements in an array.

var表示变量, arrayname是数组的名称, new是关键字, datatype表示数据的类型,例如整数,字符串和大小是数组中元素的数量。

For example,

例如,

var student = new Array[String](5)Or var student:Array[String] = new Array[String](5)

Here student is a string array that holds five elements. Values can be assigned to an array as below.

这里的Student是一个包含五个元素的字符串数组。 可以将值分配给数组,如下所示。

var student = Array("John","Adam","Rob","Reena","Harry")or student(0) = "Martin" ; student(1) = "Jack" ; student(2) = "Jill" ; student(3) = "Paul" ; student(4) = "Kevin"

Scala阵列处理 (Scala Arrays Processing)

While processing arrays we use for loop as the elements are of same data type.

在处理数组时,我们使用for循环,因为元素具有相同的数据类型。

Consider an example below.

考虑下面的示例。

object Student {def main(args: Array[String]) {var marks = Array(75,80,92,76,54)println("Array elements are : ")for ( m1 <- marks ) {println(m1 )}var gtot = 0.0for ( a <- 0 to (marks.length - 1)) {gtot += marks(a);}println("Grand Total : " + gtot);var average = 0.0average = gtot/5;println("Average : " + average);
}
}

Here we are creating marks array of Integer data type. We are printing the elements of an array using for loop. We are calculating the total marks by adding all the elements and calculate average by dividing the total by the number of subjects.

在这里,我们正在创建Integer数据类型的marks数组。 我们正在使用for循环打印数组的元素。 我们正在通过添加所有元素来计算总分,并通过将总分除以受试者数来计算平均值。

Below image shows the execution of above program.

下图显示了以上程序的执行。

Scala多维数组 (Scala Multi Dimensional Arrays)

Multidimensional arrays can be defined as an Array whose elements are arrays.

多维数组可以定义为元素为数组的Array。

Consider an example below.

考虑下面的示例。

object Multidim {
def main(args:Array[String]) {val rows = 2val cols = 3val multidim = Array.ofDim[String](rows,cols)multidim(0)(0) = "Reena"multidim(0)(1) = "John"multidim(0)(2) = "Adam"multidim(1)(0) = "Michael"multidim(1)(1) = "Smith"multidim(1)(2) = "Steve"for {i <- 0 until rowsj <- 0 until cols}println(s"($i)($j) = ${multidim(i)(j)}")}
}

We are creating a two dimensional array with 2 rows and 3 columns using the ofDim method which accepts rows and columns as arguments. Add the elements to the array as rows and columns accepting string arguments. We are using for loop retrieve the inserted elements.

我们使用ofDim方法创建一个包含2行3列的二维数组,该方法接受行和列作为参数。 将元素作为接受字符串参数的行和列添加到数组中。 我们使用for循环检索插入的元素。

Save the above code in Multidim.scala and run as shown in below image.

将上面的代码保存在Multidim.scala ,然后如下图所示运行。

Scala连接数组 (Scala Concatenate Arrays)

Two arrays can be concatenated using the concat method. Array names can be passed as an argument to the concat method.

可以使用concat方法连接两个数组。 数组名称可以作为参数传递给concat方法。

Below is an example showing how to concatenate two arrays.

下面是显示如何连接两个数组的示例。

import Array._object Student {def main(args: Array[String]) {var sname = Array("John","Adam","Rob","Reena","Harry")      var sname1 = Array("Jack","Jill","Henry","Mary","Rohan")var names =  concat( sname, sname1)println("Student name array elements are  : ");for ( n1 <- names ) {println( n1 )}}
}

We have to use import Array._ since the array methods concat is defined in the package. We have declared two arrays sname and sname1 having student names as the elements. We are concatenating these two arrays using concat method and passing sname and sname1 as arguments and storing the resultant elements in names array.

我们必须使用import Array._因为数组方法concat是在包中定义的。 我们已经声明了两个数组snamesname1 ,它们以学生姓名为元素。 我们使用concat方法连接这两个数组,并将sname和sname1作为参数传递,并将结果元素存储在names数组中。

Save the code in Student.scala and then compile and run as shown in below image.

将代码保存在Student.scala ,然后如下图所示编译并运行。

具有范围的Scala数组 (Scala Array with range)

The range() method generates an array containing sequence of integers. The final argument is used as a step to generate the sequence of integers. If the argument is not specified then the default value assumed is 1.

range()方法生成一个包含整数序列的数组。 最后一个参数用作生成整数序列的步骤。 如果未指定参数,则默认值为1。

Let us understand this range method through an example.

让我们通过一个例子来了解这种范围方法。

import Array._object Student {def main(args: Array[String]) {var id = range(7, 23, 3)var age = range(15,20)for ( s <- id ) {print( " " + s)}println()for ( a <- age ) {print( " " + a )}}
}

We are declaring arrays id and age and generating the elements using range method. The elements start from 7 to 23 incrementing by 3. For the age the increment value by 1 starting from 15 until 20.

我们声明数组id和age并使用range方法生成元素。 元素从7到23递增3。对于年龄,从15到20递增1。

Run the above code by typing Student.main(null) and you will see below output.

通过键入Student.main(null)运行以上代码,您将看到以下输出。

7 10 13 16 19 2215 16 17 18 19

Before I conclude the post, below are some useful Array methods:

在结束本文之前,下面是一些有用的Array方法:

  1. def concat[T]( xss: Array[T]* ): Array[T]: Concatenates all arrays into a single arraydef concat [T](xss:Array [T] *):Array [T] :将所有数组合并为一个数组
  2. def empty[T]: Array[T]: Returns an array of length 0def empty [T]:Array [T] :返回长度为0的数组
  3. def ofDim[T]( n1: Int, n2: Int ): Array[Array[T]]: Creates a 2-dimensional arraydef ofDim [T](n1:Int,n2:Int):Array [Array [T]] :创建二维数组
  4. def range( start: Int, end: Int, step: Int ): Array[Int]: Returns an array containing equally spaced values in some integer intervaldef range(开始:Int,结束:Int,步骤:Int):Array [Int] :返回一个数组,该数组包含某个整数间隔中的等距值
  5. def copy( src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int ): Unit: Copy one array to anotherdef copy(src:AnyRef,srcPos:Int,dest:AnyRef,destPos:Int,length:Int):单位 :将一个数组复制到另一个
  6. def ofDim[T]( n1: Int, n2: Int, n3: Int ): Array[Array[Array[T]]]: Creates a 3-dimensional arraydef ofDim [T](n1:Int,n2:Int,n3:Int):Array [Array [Array [T]]] :创建一个3维数组

That’s all for arrays in Scala programming, we will look into other scala features in future posts.

这就是Scala编程中数组的全部内容,我们将在以后的文章中探讨其他scala功能。

翻译自: https://www.journaldev.com/7915/scala-arrays-example

scala代码示例

scala代码示例_Scala数组示例相关推荐

  1. scala代码示例_Scala集合示例

    scala代码示例 Scala Collections are the containers that hold sequenced linear set of items like List, Se ...

  2. scala代码示例_Scala注释示例

    scala代码示例 Scala Annotations are metadata or extra information added to the program source code. Like ...

  3. scala代码示例_Scala异常处理示例

    scala代码示例 Scala Exception handling is similar to exception handling in Java. However Scala does not ...

  4. scala 连接符_Scala标识符示例教程

    scala 连接符 The names of variables, classes, objects and methods are collectively called Identifiers. ...

  5. scala代码示例_Scala元组和地图示例

    scala代码示例 Scala tuple is a collection of items together of different data types. Scala tuple is immu ...

  6. php object 数组赋值,php object转数组示例

    原本是这样格式的数据: object(Thrift\Server\PageCards)#32 (3) { ["cards"]=> array(10) { [0]=> o ...

  7. boost::sort模块实现在大多数排序的数组示例上展开排序

    boost::sort模块实现在大多数排序的数组示例上展开排序 实现功能 C++实现代码 实现功能 boost::sort模块实现在大多数排序的数组示例上展开排序 C++实现代码 #include & ...

  8. 分割成数组php字符串函数,PHP 分割字符串函数把字符串分割成数组示例

    这篇文章主要为大家详细介绍了PHP 分割字符串函数把字符串分割成数组示例,具有一定的参考价值,可以用来参考一下. 对PHP分割字符串函数把字符串分割成数组感兴趣的小伙伴,下面一起跟随512笔记的小编两 ...

  9. 接收对象数组_示例: Bit数组

    " 本文来源于<The Go Programming Language>" 6.5. 示例: Bit数组 Go语言里的集合一般会用map[T]bool这种形式来表示,T ...

最新文章

  1. linux内核在什么目录结构,Linux Kernel 目录结构说明
  2. C#操作Office.word(三)
  3. 想和你一起为 Visual Studio 庆祝20岁生日
  4. Python 测试(一)—— doctest
  5. Android Studio如何创建尺寸以及API通用的模拟器
  6. 移动端web轮播图插件swiper,功能很强大
  7. 微软Windows Hello曝漏洞!外接一个USB摄像头,分分钟破解你的电脑
  8. 领域驱动设计实践合订版(战略+战术)
  9. 用vs code 搭建stm32 开发环境(详细)
  10. Threejs中使用A*算法寻路导航,Threejs室内室外地图导航
  11. java 一年有多少周_Java8根据一年中的第几周获得Monday
  12. 用计算机绘图课件,第7章 计算机绘图ppt课件.ppt
  13. java算法合集-九阳神功第三式滑动窗口
  14. python打开文件代码-python_文件操作代码实例
  15. NLP系列(10)_词向量之图解Word2vec
  16. 【win10的anaconda3搭建theano环境】超详细必成功全套教程
  17. 赤橙黄绿青蓝紫html颜色,赤橙黄绿青蓝紫七种颜色的代码?
  18. 手游神武2最新服务器,神武2手游新服开启公告 安卓IOS新服开启
  19. 用python实现随机生成银行卡号,输出卡号和密码信息
  20. html测试题英语,北大PKU-GATE考试真题-题库

热门文章

  1. 预处理语句--#define、#error和#warning
  2. Cheatsheet: 2014 03.01 ~ 03.31
  3. ASP.NET MVC5+EF6+EasyUI 后台管理系统(28)-系统小结
  4. Time complexity analysis of algorithms
  5. [转载] Python中不可变集合的使用frozenset()方法
  6. [转载] python随笔2(列表的增删改查)
  7. java/android 做题中整理的碎片小贴士(15)
  8. Python_60之迭代器模块
  9. 林森---博客园之二,对《闭包》的个人见解!希望能帮到不理解闭包的同学们!...
  10. 最新出炉程序猿使用说明书