尝试用Java创建一个堆栈计算器

发布于 2024-12-10 22:02:55 字数 347 浏览 0 评论 0原文

我必须记住操作的优先级,包括答案在内的所有数字都是整数(对我来说似乎很愚蠢,但无论如何),并且我必须解析方程式的字符串,并且据我所知,推动每个在比较它们之前,先将数字和两个不同堆栈中的每个运算符进行比较。

我不知道如何解决这个问题,现在我主要关心的是处理括号。我想使用递归方法来解决计算,该方法将检查括号并解决它们并将它们替换为结果,但我不知道该怎么做。我可以使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寒尘 2024-12-17 22:02:55

我的建议是你研究调车场算法,当你有具体的关于它如何工作或如何实现其某些部分的问题。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文