Ahmed El-Salamony
Ahmed El-Salamony

Reputation: 11

Scala nested for loop

I'm a new Scala fellow and using processing library in scala ,I have 2 questions here:

 val grid: Array[Cell] = Array()              
 val w = 60   
 val rows = height/w   
 val cols = width /w

 override def setup(): Unit = {  
   for(j <- 0 until rows;   
       i <- 0 until cols){   
   val cell = new Cell(i,j)   
   grid :+ cell   
   println(s"at row : $j, at col: $i") //it compiles only once (at row : 0, 
   }                                    //at col: 0 )                                          
}
override def draw(): Unit = {
  background(0)
  grid.foreach(cell => cell.display())//nothing happens
} 

but if i replace the variables rows & cols by height/w & width/w in the nested loop as follows:

     for(j <- 0 until height/w;   
         i <- 0 until width/w){   
     val cell = new Cell(i,j)   
     grid :+ cell   
     println(s"at row : $j, at col: $i") //it compiles ordinary as nested 
        }                                 //for loop 

the second question is in the class Cell here:

   class Cell(i: Int,j:Int){

     def display(): Unit = {
       val x = this.i * w
       val y = this.j * w

       println("it works")//doesn't work
       //creating a square
       stroke(255)
       line(x,y,x+w,y)//top
       line(x+w,y,x+x,y+w)//right
       line(x,y+w,x+w,y+w)//bottom
       line(x,y,x,y+w)//left

   }
 }

the method display doesn't work when calling at function draw() but no errors show up

Upvotes: 1

Views: 390

Answers (1)

Tim
Tim

Reputation: 27356

Use tabulate to initialise your Array:

val grid = Array.tabulate(rows * cols) { i => new Cell(i % cols, i / cols) }

If you still have a problem with the display function then please post it as a separate question.

Upvotes: 1

Related Questions