尝试用Java创建一个堆栈计算器
我必须记住操作的优先级,包括答案在内的所有数字都是整数(对我来说似乎很愚蠢,但无论如何),并且我必须解析方程式的字符串,并且据我所知,推动每个在比较它们之前,先将数字和两个不同堆栈中的每个运算符进行比较。
我不知道如何解决这个问题,现在我主要关心的是处理括号。我想使用递归方法来解决计算,该方法将检查括号并解决它们并将它们替换为结果,但我不知道该怎么做。我可以使用 substring()
和 indexOf()
但我宁愿更优雅。
除此之外,我不确定一旦数字和运算符堆叠起来如何解决计算。我认为我应该比较前 2 个运算符,以确保如果我组合两个数字,它的运算顺序正确,但我也不想在这部分上变得笨拙。
I have to keep in mind the priority of operations, all the numbers including the answer are integers (seems silly to me but whatever), and I have to parse a String for the equation and, as far as I'm aware, push each number and each operator in two different stacks before I compare them.
I don't know how to approach this problem, and right now my main concern is dealing with parentheses. I want to use a recursive method to solve the calculation which would check for parentheses and solve them and replace them with their result, but I'm not sure how to do that. I could use substring()
and indexOf()
but I'd rather be more elegant.
Other than that I'm not sure how to solve the calculation once numbers and operators are stacked. I think I should compare the top 2 operators to make sure that if I combine two numbers, it is in the right order of operations, but I don't want to be clumsy with that part either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的建议是你研究调车场算法,当你有具体的关于它如何工作或如何实现其某些部分的问题。
My recommendation would be that you study the Shunting-yard algorithm and come back when you have specific questions about how it works or how to implement certain parts of it.