How does one update and print a 'Rational' token in javacc?
I have added the new token RATIONAL that recognises rational numbers on my JavaCC parser. How can I update the output part of the program to print the numeric value of the rational number?
For example ('2/5') value = 0.4, ('8/2') value = 4.0开发者_如何学JAVA, ('4/0') value = infinity.
I will be grateful if anyone could help me. Thanks.
You need to further split the image of your RATIONAL token in order to have both numbers available for computation.
It's not clear from your question whether the parentheses and quotes are part of the defined syntax. If they are, you can easily define them as delimiters for a rational expression and define tokens for the numbers and the slash. In case of ambiguity with other places where numbers can appear, remember that lexical states are your friends.
If a rational expression is simply made of two numbers separated by a slash, then I'd recommend building an AST and evaluate it after the parsing is complete. You can alternatively evaluate it during the parsing, but the difficulty of this depends on the rest of your grammar.
精彩评论