“理性” Javacc 中的令牌
如何在 javacc 中创建一个“有理数”标记,它接受一个有理数并计算其值。敌人示例“2/5”值=0.4。我知道如何为此编写正则表达式,但不知道并且从未正确地教授过如何/在何处将 java 方法合并到 javacc 代码中。我被告知:
请注意,分母为 0 的有理数是未定义的。而不是产生错误, 打印无穷大,如上所示。 建议:您可以按顺序使用 Java String 类中的 indexOf 和 substring 方法 提取有理数的分子和分母部分。这是个好主意 定义第二个变量(例如 val2)以存储分母的值。另外,还投 除以 double 的结果即 (double) val / val2。
请记住,我是 javacc 的新手,但有 java 的基本知识。任何有关此事的建议将不胜感激。非常感谢。
How does one create a 'Rational' token in javacc that takes a rational number and calculates its value. Foe example '2/5' value =0.4. I know how to write a regex for this, but don't know, and have never been properly taught, how to/where to incorporate java methods in javacc code. I have been advised that:
Note that rational numbers with 0 denominator are undefined. Instead of generating an error,
print infinity, as shown above.
Advice: You can use the indexOf and substring methods from the Java String class in order
to extract the numerator and denominator parts of your rational number. It’s a good idea to
define a second variable (e.g. val2) in order store the value of your denominator. Also, cast
the result of the division to double i.e. (double) val / val2.
Bear in mind that I'm new to javacc, but have a basic knowledge of java. Any advice on this matter will be greatly appreciated. Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果语法中没有与选择点相关的问题,您可以使用以下语法:
但是这种方法使 JavaCC 将“令牌”parse_rational 视为黑匣子,这就是为什么在选择中使用它的原因(例如:
S(): { parse_rational() | SomethingElse }
我不知道你是否需要编写一个完整的编译器或只是一个分数解析器,如果答案是第二个,那么这个东西可以很好地工作 。 ..
If there aren't problems related to choice points inside your grammar you can use the following syntax:
But this approach makes JavaCC think about the "token" parse_rational as a black box, that's why using it in a choice (eg:
S(): { parse_rational() | SomethingElse }
it's not good.I don't know if you need to write a full compiler or just a fraction parser, if the answer is the second this thing can work quite well..