刚刚开始使用Scala。每次尝试执行它时,都会显示不匹配的错误。我只返回整数。编译器仍然从上帝知道的地方找到类型Unit
。scala:类型不匹配(找到单元,你需要int)
object a {
def search(e : Int,arr : Array[Int]): Int = {
var l: Int = 0
for(l <- 0 arr.length) {
if(arr(l) == e) {
return e
} else {
return -1
}
}
}
def main(args: Array[String]) {
var i = 0
println("enter the number of elements ")
var n = readLine.toInt
println("enter the elements are")
var arr = new Array[Int](n)
for(i <- 0 to n-1) {
println("enter element "+i+" ")
arr(i) = readLine.toInt
}
for(i <- 0 to n-1) {
println("element "+i+" is "+arr(i))
}
println("sorted array is")
arr = arr.sortWith(_ < _)
for(i <- 0 to n-1) {
println(arr(i))
}
println("enter the number to be searched ")
var e = readLine.toInt
var result: Int = search(e,arr)
if(result == e) {
println("element found")
} else {
println("element not found")
}
}
}
输出
[email protected]:~$ scalac a.scala
a.scala:6: error: type mismatch;
found : Unit
required: Int
for(l<-0 until arr.length)
^
one error found
在Scala中编写这个代码的方法可能是http://pastebin.com/UrTSsDt1 –