Shelly Verma Shelly Verma -3 years ago 160
Scala Question

how to print Scala user defined Arrays

I tried below code but it ultimately prints 5 zeros after giving the user defined values to array .

the below code takes array of size 5 and gives user defined values

object printarray {
def main(args:Array[String]) {
val arr = new Array[Int](5)

println("the values of array is ")
for(i<-0 to 4) {
val arr = scala.io.StdIn.readInt()
}

arr.foreach(println)
}
}

Answer Source

There are a couple of things that need improvement in the code.

You allocate an array of 5 elements named arr in the scope of the main method, but you also declare an additional value with the same name, arr, inside the for comprehension scope and read an Int into it, which you discard once you exit the for scope. Then, you print the array in the outer scope, which hasn't changed at all.

The first thing you need to make this work, is index into the array instead of creating a new value named arr in the inner scope:

object printarray {    
  def main(args:Array[String]) {
    val arr = new Array[Int](5)

    println("the values of array is ")
    for (i <- 0 to 4) {
      arr(i) = scala.io.StdIn.readInt()
    }

    arr.foreach(println)
  }
}

To improve things further, you use the yield Scala synax to make this more concise:

val arr = for (i <- 0 to 4) yield StdIn.readInt()

This will not return an Array[Int], but an IndexedSeq[Int] with an underlying type of Vector[Int]. If you still want an Array[Int], you'll have to explicitly call toArray:

val arr: Array[Int] = (for (i <- 0 to 4) yield scala.io.StdIn.readInt()).toArray
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download