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