Ankita
Ankita

Reputation: 480

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)
  }
}

Upvotes: 0

Views: 107

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149518

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

Upvotes: 4

Shaido
Shaido

Reputation: 28322

In your for-loop you are reassigning the variable in every iteration. You can change it to:

for(i <- 0 to 4) {
  arr(i) = scala.io.StdIn.readInt()
}

As a side-note, instead of declaring the arr before the loop you can simply do:

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

Upvotes: 2

Related Questions