I am trying to write a hangman code on scala. So, I wrote the following code for making an array that the length of elements are determined by args. For example, there exists an array B = Array("scala", "python", "C++", "Pascal", "java") and from this array I want to make an array that has an elements only of length 6. The following is the code I wrote:
import scala.io.Source
import java.util.Random
val fname = args(0)
val listOfwords = Source.fromFile(fname).getLines.toArray
val temp = Array("a")
val a = args(1).toInt
def new_array{
for (i <- 0 until 开发者_如何学GolistOfwords.length-1){
var length = listOfwords(i).length.toInt
if (length == a) {
temp :+ listOfwords(i)
}
}
}
Is this code right?
This takes advantage of the new Scala 2.8 collections... Should do what you want.
import scala.io.Source
import java.util.Random
val fname = args(0)
val listOfwords = Source.fromFile(fname).getLines.toArray
val a = args(1).toInt
val new_array = listOfwords.filter(elem => elem.length == a)
// or you can use this
val new_array = listOfwords.filter(_.length == a)
精彩评论