问题描述
在给定算术表达式的情况下,我需要一些帮助来创建自定义树.比如说,你输入这个算术表达式:
I needed some help with creating custom trees given an arithmetic expression. Say, for example, you input this arithmetic expression:
(5+2)*7
结果树应该如下所示:
*
/
+ 7
/
5 2
我有一些自定义类来表示不同类型的节点,即 PlusOp、LeafInt 等.我不需要计算表达式,只需创建树,以便稍后对其执行其他功能.另外,负运算符'-'只能有一个子节点,要表示'5-2',必须输入5+(-2).
I have some custom classes to represent the different types of nodes, i.e. PlusOp, LeafInt, etc. I don't need to evaluate the expression, just create the tree, so I can perform other functions on it later.Additionally, the negative operator '-' can only have one child, and to represent '5-2', you must input it as 5 + (-2).
需要对表达式进行一些验证以确保每种类型的运算符都具有正确的编号.在参数/子项中,每个左括号都伴随着一个右括号.
Some validation on the expression would be required to ensure each type of operator has the correct the no. of arguments/children, each opening bracket is accompanied by a closing bracket.
另外,我应该提到我的朋友已经编写了将输入字符串转换为令牌堆栈的代码,如果这对此有帮助的话.
Also, I should probably mention my friend has already written code which converts the input string into a stack of tokens, if that's going to be helpful for this.
我很感激任何帮助.谢谢:)
I'd appreciate any help at all. Thanks :)
(我读到你可以写一个语法并使用 antlr/JavaCC 等来创建解析树,但我不熟悉这些工具或编写语法,所以如果这是你的解决方案,我会如果您能为他们提供一些有用的教程/链接,我们将不胜感激.)
(I read that you can write a grammar and use antlr/JavaCC, etc. to create the parse tree, but I'm not familiar with these tools or with writing grammars, so if that's your solution, I'd be grateful if you could provide some helpful tutorials/links for them.)
推荐答案
"ANTLR 五分钟介绍" 包括一个算术语法示例.值得一试,尤其是因为 antlr 是开源的(BSD 许可).
The "Five minute introduction to ANTLR" includes an arithmetic grammar example. It's worth checking out, especially since antlr is open source (BSD license).
这篇关于在 Java 中解析算术表达式并从中构建树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!