Davide Ambrosi
Davide Ambrosi

Reputation: 37

For loop error type mismatch in Scala

i'm learning Scala, but I'm not able go trough the for loop in this code

    def adjacentElementsProduct(inputArray: Array[Int]): Int = {

    var maxSoFar = 0
    var maxHere = 0

    //for (i <- 0:Int to (inputArray.length-1))      <- error
    for (i <- 0 to inputArray.length-1)            //<- error
    {
          if( maxHere * inputArray(i) > 0 )
                maxHere *= inputArray(i)
          else
                maxHere = 0

          if( maxHere > maxSoFar )
                maxSoFar = maxHere

          maxSoFar
    }

}

Compiler results:

(without :Int)

  file.scala on line 6: error: type mismatch;
 found   : Unit
 required: Int
        for (i <- 0 to inputArray.length-1)
               ^

(with :Int)

file.scala on line 6: error: identifier expected but integer literal found.
    for (i <- 0:Int to (inputArray.length - 1) )
                                            ^
file.scala on line 19: error: ')' expected but '}' found.
}
^

What is wrong? How can i solve it?

Thanks a lot, Davide

Upvotes: 0

Views: 715

Answers (3)

jwvh
jwvh

Reputation: 51271

If what you're trying to do is return the maximum product of adjacent non-zero integers, here's a more Scala-esque approach.

def adjacentElementsProduct(inputArray: Array[Int]): Int =
  inputArray.scanLeft(0)((a,b) => if (a==0) b else a*b).max

explanation (somewhat simplified)

Think of it this way: myArray.scanLeft(init)(op) will build a new Array that looks something like:

Array( init
     , op(init,             myArray(0))
     , op(previousOpResult, myArray(1))
     , op(previousOpResult, myArray(2))
     . . .
     )

Upvotes: 2

Ziyang Liu
Ziyang Liu

Reputation: 810

adjacentElementsProduct needs to return a Int, you need to put what you want to return at the end of the method (outside the for-loop).

Also you can simplify for (i <- 0 to inputArray.length-1) to for (i <- inputArray) and replace inputArray(i) with i.

Upvotes: 2

zhangkuantian
zhangkuantian

Reputation: 21

the return value maxSoFar should out of the for loop {},like this :

def adjacentElementsProduct(inputArray: Array[Int]): Int = {

    var maxSoFar = 0
    var maxHere = 0

    //for (i <- 0:Int to (inputArray.length-1))      <- error
    for (i <- 0 to inputArray.length-1)            //<- error
    {
          if( maxHere * inputArray(i) > 0 )
                maxHere *= inputArray(i)
          else
                maxHere = 0

          if( maxHere > maxSoFar )
                maxSoFar = maxHere


    }
    maxSoFar

} 

Upvotes: 1

Related Questions