2013-03-28 81 views
0

我正在学习在Scala中编程。我有两个包名为chapter3chapter4。下面是代码:在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 

回答

1

确保您的目录结构:

chapter3/FileOperation.scala 
chapter4/Summer.scala 

然后,从父目录运行:

scalac chapter3/FileOperation.scala chapter4/Summer.scala 

这个编译就好了。如果你想单独编译它们,确保FileOperation是第一个,因为Summer取决于它。

一旦它的编译,你可以运行它:

scala -cp .:chapter3:chapter4 chapter4.Summer 
+0

它与 scalac第三章/第四章FileOperation.scala编译/ Summer.scala 然而,当我尝试运行,我得到以下错误: > scala chapter4/Summer classpath上没有这样的文件或类:chapter4/Summer – user1247412 2013-03-28 01:35:09

+0

@ user1247412为了在终端中直接使用'scala'命令运行Scala程序,您需要有一个java classpath的概念。否则,您将不得不使用已经为您设置类路径的构建工具(Eclipse/SBT ...)。 – 2013-03-28 01:43:41

+0

这将运行您的程序:scala -cp。:chapter3:chapter4 chapter4.Summer – 2013-03-28 03:12:45