Eclipse 在scala中导入对象时出错
我正在学习用Scala编程。我有两个包,分别是Eclipse 在scala中导入对象时出错,eclipse,scala,Eclipse,Scala,我正在学习用Scala编程。我有两个包,分别是第3章和第4章。代码如下: 包第3章中的文件FileOperation.scala的代码: package chapter3 import scala.io.Source object FileOperation { /** * This function determines the length of line length. */ def findLineLengthWidth(line : String) : Int
第3章
和第4章
。代码如下:
包第3章中的文件FileOperation.scala
的代码:
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)
}
}
}
当我在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
确保您的目录结构为:
chapter3/FileOperation.scala
chapter4/Summer.scala
然后,从父目录运行:
scalac chapter3/FileOperation.scala chapter4/Summer.scala
这个编译得很好。如果要单独编译它们,请确保首先执行FileOperation
,因为Summer
依赖于它
编译后,您可以使用以下工具运行它:
scala -cp .:chapter3:chapter4 chapter4.Summer
它是用scalac chapter3/FileOperation.scala chapter4/Summer.scala编译的,但是当我尝试运行时,我得到以下错误:>scala chapter4/Summer类路径上没有这样的文件或类:chapter4/Summer@user1247412为了直接使用Scala
命令在终端中运行Scala程序,您需要有java类路径的概念。否则,您将不得不使用已经为您设置了类路径的构建工具(Eclipse/SBT…)。这将运行您的程序:scala-cp.:chapter3:chapter4 chapter4.summer没有任何简单的方法来编译和运行来自不同包的文件吗?可以从以下方面考虑:1)编译传递给编译器的所有内容,2)然后将结果放在类路径上,3)运行一个具有main()方法的对象。上面的示例已经使用了2个包。
scala -cp .:chapter3:chapter4 chapter4.Summer