ArrayIndexOutofBoundException在Scala Program Usind VTD-XML中

时间:2011-02-26 11:48:18

标签: scala vtd-xml scala-xml

    import java.lang._

    import com.ximpleware._

    object Sample {

      def  main(args :Array[String])=  {

        // println("helloo")

         try{
             var i :Int = -1

             val vgen :VTDGen= new VTDGen()
             val ap :AutoPilot =new AutoPilot()


             ap.selectXPath("CATALOG/CD/COUNTRY/text()")
             if(vgen.parseFile("../catalog.xml", false)) {
                 val vnav :VTDNav = vgen.getNav()

                 ap.bind(vnav)

                 while((i=ap.evalXPath)!= -1) {


                  println(vnav.toString(i))
                  println(vnav.toNormalizedString(vnav.getText()))
            }

           ap.resetXPath()
         }
      }
      catch {
          case e :Exception => println(e)
      }
     }
    }

我导入了VTD-XML库 它编译得很好,但On Execution打印出一个例外

:java.lang.ArrayIndexOutOfBoundsException: -1

我已经解决了代码中的while问题。但问题是ap.evalXPAth

总是得-1

2 个答案:

答案 0 :(得分:4)

我相信答案就在于行

while((i=ap.evalXPath)!= -1) {

在Scala赋值中返回Unit(相当于Java中的void),因此该循环无法终止。例如,如下程序无限循环

scala> var i = 0
i: Int = 0

scala> while((i = i + 1) != 10) { println(i) }
<console>:7: warning: comparing values of types Unit and Int using `!=' will always yield true
       while((i = i + 1) != 10) { println(i) }

答案 1 :(得分:1)

John McCrae说;虽然检查不会在scala中飞行。相反,你可以为-1结束调用定义一个新的while结构:

def whileNotEmpty(whileF: () => Int)(doF: (Int) => Unit): Unit = { 
  val n = whileF()
  if (n != -1) { 
    doF(n)
    whileNotEmpty(whileF)(doF) 
  } 
}

这是从键盘读取的调用的简化示例,直到您给出-1:

whileNotEmpty(() => Console.readLine.toInt) { 
  n => println(n) 
}