scala中打印数组和集合_如何在Scala中打印数组?

本文介绍了Scala中的数组数据结构,以及如何通过迭代和字符串转换两种方式来打印数组的所有元素。详细阐述了创建和访问数组的方法,并提供了具体的语法示例。
摘要由CSDN通过智能技术生成

scala中打印数组和集合

Scala中的数组 (Array in Scala)

In Scala, Array is a data structure that is a collection of elements of same data type.

在Scala中,数组是一种数据结构,是相同数据类型的元素的集合。

Creating an array:

创建一个数组:

The Array keyword is used to create an array in Scala. There are multiple syntaxes to create an array. They are,

Array关键字用于在Scala中创建数组。 创建数组有多种语法。 他们是,

    var array_name : Array[data_type] = new Array[data_type(size) 
    var array_name: Array[data_tpye] = new Array(size)
    var array_name = new Array[data_type](size) 
    var array_name = Array(element1, elmenet2, element3, ...)

All the four declarations are valid but the last two are commonly used.

这四个声明都是有效的,但最后两个是常用的。

Accessing an element from the array:

从数组访问元素:

To access the element of the array, its index is used.

要访问数组的元素,请使用其索引。

Syntax:

句法:

    array_name[index]

打印阵列 (Print Array)

There are two methods to print all the elements of the array (print array):

有两种方法可以打印数组的所有元素(打印数组):

  1. Using iteration

    使用迭代

  2. Using string conversion

    使用字符串转换

1)使用迭代打印数组元素 (1) Printing elements of array using iteration)

We can print the elements of the array by integrating over all the elements of the array and then printing each element using their index.

我们可以通过对数组的所有元素进行积分,然后使用它们的索引来打印每个元素,来打印数组的元素。

Syntax:

句法:

    for(i 

Program to print array using iteration

Output:

Elements of Array are : 
97 90 89 75 45 78 99

Explanation:

In the above code, we have created an array of integer values and then use the for loop to iterate over the elements of the array using the print statement.

2) Printing elements of the array using string conversion method

We can print array using the string conversion method, i.e. converting the array to a string using mkString() method.

Syntax:

Program to print array using string conversion method

object MyClass {
    
    def main(args: Array[String]) {
    
        var score = Array("C", "C++", "Java", "Python", "Scala")   
        va
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值