1

这是一段简单的代码:

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

那么我错过了什么?

4

1 回答 1

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"));
    }
}

于 2009-08-26T18:40:11.747 回答