Question

(Scala 2.7.7:) I don't get used to 2d-Arrays. Arrays are mutable, but how do I specify a 2d-Array which is - let's say of size 3x4. The dimension (2D) is fixed, but the size per dimension shall be initializable. I tried this:

class Field (val rows: Int, val cols: Int, sc: java.util.Scanner) {
 var field = new Array [Char](rows)(cols)

 for (r <- (1 to rows)) {
  val line = sc.nextLine ()
  val spl = line.split (" ")
  field (r) = spl.map (_.charAt (0))
 }

   def put (row: Int, col: Int, c: Char) =
       todo ()
}

I get this error: :11: error: value update is not a member of Char field (r) = spl.map (_.charAt (0))

If it would be Java, it would be much more code, but I would know how to do it, so I show what I mean:

public class Field
{
 private char[][] field;

 public Field (int rows, int cols, java.util.Scanner sc) 
 {
  field = new char [rows][cols]; 
  for (int r = 0; r < rows; ++r) 
  {
   String line = sc.nextLine ();
   String[] spl = line.split (" ");
   for (int c = 0; c < cols; ++c)
    field [r][c] = spl[c].charAt (0);
  }
 }

 public static void main (String args[])
 {
  new Field (3, 4, new java.util.Scanner ("fraese.fld"));
 }
}

and fraese.fld would look, for example, like that:

M M M 
M . M 

I get some steps wide with

val field = new Array [Array [Char]](rows)

but how would I then implement 'put'? Or is there a better way to implement the 2D-Array. Yes, I could use a one-dim-Array, and work with

put (y, x, c) = field (y * width + x) = c

but I would prefer a notation which looks more 2d-ish.

Was it helpful?

Solution

for (r <- (1 to rows)) {

Should this be:

for (r <- (0 to rows - 1)) {

... starting from 0 instead of 1?

field (r) = spl.map (_.charAt (0))

Should this use the operator syntax, like this:

field (r) = spl map (_.charAt (0))

... without the '.' between spl and map?


This is my version - I replaced the Scanner with an Array[String] since I'm not really sure what the input for the scanner is supposed to be. It compiles and runs on Scala 2.7.5:

class Field (val rows: Int, val cols: Int, lines: Array[String]) {
    var field = new Array [Array[Char]](rows)

    // These get replaced later on, but this is how to initialize a 2D array.
    for (i <- (0 to rows - 1)) {
        field(i) = new Array[Char](cols)
    }

    for (r <- (0 to rows - 1)) {
        val line = lines(r)
        val spl = line.split (" ")
        field(r) = spl map (_.charAt (0))
    }
}

var lines = Array[String] ("A A A A A", "B B B B B", "C C C C C", "D D D D D", "E E E E E")
var test  = new Field(5, 5, lines)
test.field
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top