Jparsec - 解析简单数字

时间:2009-08-25 20:24:41

标签: java jparsec

这是一段简单的代码:

import org.codehaus.jparsec.Parser;
import org.codehaus.jparsec.Terminals;
import org.codehaus.jparsec.functors.Map;

public class Test {
  static final Parser<Double> NUMBER = Terminals.DecimalLiteral.PARSER.map(
    new Map<String, Double>() {
      public Double map(String s){
        return Double.valueOf(s);
    }
  });

  public static void main(String[] args) {
    System.out.println(NUMBER.parse("234234234"));
  }
}

应该打印出一个数字,即234234234.而是打印出来:

Exception in thread "main" org.codehaus.jparsec.error.ParserException: Parser not on token level
line 1, column 1
    at org.codehaus.jparsec.Parser.asParserException(Parser.java:673)
    at org.codehaus.jparsec.Parser.run(Parser.java:682)
    at org.codehaus.jparsec.MapParser.apply(MapParser.java:30)
    at org.codehaus.jparsec.Parser.run(Parser.java:679)
    at org.codehaus.jparsec.Sequence2Parser.apply(Sequence2Parser.java:32)
    at org.codehaus.jparsec.Parser.run(Parser.java:679)
    at org.codehaus.jparsec.Parsers.parse(Parsers.java:97)
    at org.codehaus.jparsec.Parser.parse(Parser.java:617)
    at org.codehaus.jparsec.Parser.parse(Parser.java:628)
    at org.codehaus.jparsec.Parser.parse(Parser.java:633)
    at Test.main(Test.java:51)
Caused by: java.lang.IllegalStateException: Parser not on token level
    at org.codehaus.jparsec.ScannerState.getToken(ScannerState.java:68)
    at org.codehaus.jparsec.IsTokenParser.apply(IsTokenParser.java:30)
    at org.codehaus.jparsec.Parser.run(Parser.java:679)
    ... 9 more

那么我错过了什么?

1 个答案:

答案 0 :(得分:0)

我不是jparsec的专家,但NUMBER的以下替代定义似乎有效:


import org.codehaus.jparsec.Parser;
import org.codehaus.jparsec.Terminals;
import org.codehaus.jparsec.Tokens.Fragment;
import org.codehaus.jparsec.functors.Map;

public class Test
{
    static final Parser NUMBER = Terminals.DecimalLiteral.TOKENIZER.map(
            new Map<Fragment, Double>() {
                public Double map(Fragment arg0) {
                    return Double.valueOf(arg0.text());
                }
            });

    public static void main(String[] args)
    {
        System.out.println(NUMBER.parse("234234234"));
    }
}