0

I have a problem where it gives me an error "'[' expected but integer literal found" at initializing the array the string array "arr[i][j]="string";" for all my initialization. I want to display this 2D array in a table in the HTML view.

1
  • 2
    Please try arr(i)(j)="string". You can access elements of the array with () not []. Also, remember to use the mutable array. Commented Apr 24, 2019 at 12:22

1 Answer 1

0

As this answer specifies Java array maps directly into Scala ones. And also, in Scala, to access an element in a collection, you need to use the apply() method, which is equivalent to the ():


val arr = Array.fill(3,3)("hello")
// Displays
//arr: Array[Array[String]] = Array(
//  Array("hello", "hello", "hello"),
//  Array("hello", "hello", "hello"),
//  Array("hello", "hello", "hello")
//)

val row0 = arr.apply(0)
//Displays
//row0: Array[String] = Array("hello", "hello", "hello")

val row1 = arr(1)
//Display
//row1: Array[String] = Array("hello", "hello", "hello")

val elem11 = row1(1)
//elem11: String = "hello"

Here is how you can update an element:

arr(1)(1) = "string"

arr.map(_.mkString(",")).mkString("\n")
// Displays
//res9: String = """hello,hello,hello
//hello,string,hello
//hello,hello,hello"

Sign up to request clarification or add additional context in comments.

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.