0
我正在学习在Scala中编程。我有两个包名为chapter3
和chapter4
。下面是代码:在scala中导入对象时出错
代码文件FileOperation.scala
封装chapter3
:在第4章包文件
package chapter3
import scala.io.Source
object FileOperation {
/**
* This function determines the length of line length.
*/
def findLineLengthWidth(line : String) : Int = {
val len = line.length.toString.length()
return len;
}
def readFile(filename : String) {
val lines = Source.fromFile(filename).getLines().toList
val longestLine = lines.reduceLeft((a, b) => if(a.length > b.length) a else b)
val maxlength = findLineLengthWidth(longestLine)
for (line <- lines) {
val len = findLineLengthWidth(line)
val spacecount = (maxlength - len)
val padding = " " * spacecount
println(padding + line.length +"|"+ line)
}
}
}
代码:Summer.scala
package chapter4
import chapter3.FileOperation._
object Summer {
def main(args: Array[String]): Unit = {
{
//val file = new FileOperation
readFile("abc.txt")
}
}
}
当我在Eclipse中运行这段代码,它工作正常。然而,当我尝试编译它在终端,我得到以下错误:
$ scalac *.scala
Summer.scala:3: error: not found: object chapter3
import chapter3.FileOperation._
^
Summer.scala:11: error: not found: value readFile
readFile("abc.txt")
^
two errors found
它与 scalac第三章/第四章FileOperation.scala编译/ Summer.scala 然而,当我尝试运行,我得到以下错误: > scala chapter4/Summer classpath上没有这样的文件或类:chapter4/Summer – user1247412 2013-03-28 01:35:09
@ user1247412为了在终端中直接使用'scala'命令运行Scala程序,您需要有一个java classpath的概念。否则,您将不得不使用已经为您设置类路径的构建工具(Eclipse/SBT ...)。 – 2013-03-28 01:43:41
这将运行您的程序:scala -cp。:chapter3:chapter4 chapter4.Summer – 2013-03-28 03:12:45