2

I am trying following but getting error "variable arr of type Array[Int] does not take type parameters."

object try_arr
{
  def main(args: Array[String])
  {
    var arr = new Array[Int](3)
        for(i<- 1 to 3)
        {
          val num = scala.io.StdIn.readInt()
          arr[i] = num
        }
      }
    }

5 Answers 5

5

As already pointed out by Simon, you're trying to apply java syntax to scala code -- in scala [ ] are used to specify type and in order to access array elements you're shall use (), e.g. xs(3)

I guess the cleanest way to solve this is to make use of Array.fill method:

object FillTheArray {
  def main(args: Array[String]) {
    val userInput = Array.fill(3) {
      scala.io.StdIn.readInt()
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

In scala you index the array like this

arr(i) = num

Comments

2

Use below statement

a(i)= scala.io.StdIn.readInt()

1 Comment

While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
1

More of a side note, consider this more Scalish approach with immutable objects,

val xs = for (i <- 1 to 3; num = scala.io.StdIn.readInt()) yield num 

where each value in the range (1 to 3) is mapped onto a user input. The resulting vector (xs) may be converted to an array,

xs.toArray

Likewise

(1 to 3).map(_ => scala.io.StdIn.readInt()).toArray

proves terser a code.

This is in contrast with the more imperative approach to creating a mutable array, and updating each position (referred by each value in the range) with a user input.

Comments

0

in for loop can't 1 to 3 because array index start in 0 and beetween 0 to 2. Else shows error ArrayOutOfBound Exception.

Code : var arr = new ArrayInt

    for(i<- 0 to 2)
    {
        print("Enter number")
        val num = scala.io.StdIn.readInt()
        arr(i) = num
    }
    arr.foreach((element:Int)=> print(element + " "))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.