所以我今天下午开始学习Scala,当我尝试使用标准scalac Sqrt.scala
和scala Sqrt
运行我的程序时,很快就出现了停止点:
java.lang.NoSuchMethodException: Sqrt.main is not static
at scala.reflect.internal.util.ScalaClassLoader$class.run(ScalaClassLoader.scala:68)
at scala.reflect.internal.util.ScalaClassLoader$URLClassLoader.run(ScalaClassLoader.scala:101)
at scala.tools.nsc.CommonRunner$class.run(ObjectRunner.scala:22)
at scala.tools.nsc.ObjectRunner$.run(ObjectRunner.scala:39)
at scala.tools.nsc.CommonRunner$class.runAndCatch(ObjectRunner.scala:29)
at scala.tools.nsc.ObjectRunner$.runAndCatch(ObjectRunner.scala:39)
at scala.tools.nsc.MainGenericRunner.runTarget$1(MainGenericRunner.scala:65)
at scala.tools.nsc.MainGenericRunner.run$1(MainGenericRunner.scala:87)
at scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:98)
at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:103)
at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)
这是我的Sqrt.scala的代码:
class Sqrt {
val PRECISION = 0.01
def abs(d: Double): Double =
if (d >= 0) d else -d
def isCloseEnough(guess: Double, x: Double): Boolean =
abs(guess * guess - x) < PRECISION
def improve(guess: Double, x: Double): Double =
(x/guess + guess)/2
def iter(guess: Double, x: Double): Double =
if(isCloseEnough(guess, x)) guess
else iter(improve(guess, x), x)
def sqrt(x: Double): Double =
iter(1, x)
def main(args: Array[String]) {
println(sqrt(16))
}
}
有人可以提出解释吗?
答案 0 :(得分:4)
object Sqrt
代替class Sqrt
看看Scala开始使用:http://www.scala-lang.org/documentation/getting-started.html
此外,不推荐使用您正在使用的main函数的语法,它应该是:
def main(args: Array[String]):Unit = {}
。