How to create an Array in Scala

Scala array FAQ: How do I create an array in Scala?

The syntax for declaring an array variable is var arrayname = newArray[datatype](size)

There are a few different ways to create String arrays in Scala. If you know all your array elements initially, you can create a Scala string array like this:

val fruits = Array("Apple", "Banana", "Orange")

If you don't know the strings that you want in your array initially, but know the size of your array, you can create it first, then populate it later, like this:

val fruits = new Array[String](3)

// somewhere later in the code ...

fruits(0) = "Apple"
fruits(1) = "Banana"
fruits(2) = "Orange"

Mutable Scala String arrays

Note that if you want to create a mutable Scala String array, you really want to use the ScalaArrayBufferclass instead of the Array class, like this:

import scala.collection.mutable.ArrayBuffer
var fruits = ArrayBuffer[String]()
fruits += "Apple"
fruits += "Banana"
fruits += "Orange"

How to handle the items in an Array

object Student {
   def main(args: Array[String]) {
      var marks = Array(75,80,92,76,54)   <<<< create an array with initial items

      println("Array elements are : ")
        for ( m1 <- marks ) {
         println(m1 )
      }

      var gtot = 0.0
      for ( a <- 0 to (marks.length - 1)) {
         gtot += marks(a);
      }
      println("Grand Total : " + gtot);

 var average = 0.0
 average = gtot/5;
 println("Average : " + average);
}
}

results matching ""

    No results matching ""