如何将Java泛型应用于计算器?
我正在做作业。
首先,有一个任务是制作计算器,它可以计算这样的表达式:5*(2+1)。
现在,我有新的任务。根据输入参数,必须以不同类型(Integer、Double、Long、Float)计算表达式。我应该使用泛型。
问题是我无法理解如何在程序结构中实现它。现在,我将尝试对其进行简要描述。
类令牌 {char kind, double value} - 包含令牌。
Class TokenStream - 将表达式拆分为标记。
Class Parser - 构建解析树,并以逆波兰表示法保存标记
Class Evaluator - 评估 RPN
Class Calc - 包含主要功能
教师建议use:
interface Operation<E> {
E parse(String)
E add(E e1, E e2)
...
}
IntOperation implements Operation<Integer> {...}
我不明白该怎么做以及他的意思是什么。你能给点建议吗?
PS:抱歉我的英语:)
I'am doing homework.
Firstly, there was a task to make calculator, which can evaluate such expressions: 5*(2+1).
Now, I have new task. Depending on the input parameter, the expression must be calculated in different types (Integer, Double, Long, Float). And I should use generics.
The problem is that I can't understand how to implement this in program's structure. Now, I'll try to describe it in brief.
Class Token {char kind, double value} - contains token.
Class TokenStream - splits the expression into tokens.
Class Parser - builds a parse tree, and saves tokens in Reverse Polish Notation
Class Evaluator - evaluates RPN
Class Calc - contains main function
Teacher advised to use:
interface Operation<E> {
E parse(String)
E add(E e1, E e2)
...
}
IntOperation implements Operation<Integer> {...}
I don't understand how to do this and what did he mean. Can you advice something?
PS: Sorry for my english:)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的主要问题是你使用的是原始类型,如 int、long、double 等,而不是对象。当您使用泛型时,首先要记住的规则是泛型仅适用于对象类型。在这种情况下将是 Integer、Long、Double 等。
重要信息四您的情况是,Java 中的所有数字对象都应该扩展 Number 类。当我们知道这一点时,解决方案的图片就开始出现。
然后,将实现此接口的类将处理所有数字类型。
例如,对于 Long.class,其实现如下:
PS。我用过你的界面设计。但我认为解析和计算的逻辑应该分开。这意味着只有一个接口可以执行解析操作并计算结果。您应该有两个接口,第一个用于解析,第二个用于计算。例如,您将来可以只传递数字,而不传递带有表达式的字符串。
那么设计思路:
以及示例实现:
Your main problem is that you are using primitive type like int, long, double etc. insted of Objects. When you are working with Generics firs rule to remember is that generics work only on Object type. In this case would be Integer, Long, Double etc.
Important information four your case is that, all numeric Object in Java should extend the Number class. When we know this a picture of solution is start to came up.
Then a class that will implement this interface, would handle all numeric types.
For example for Long.class the implementation goes like this:
PS. I have used your interface design. But i think that the logic of parse and calculation should be separated. This mean that instead having one interface that perform parse operation and also calculate the result. You should have two interfaces one for parse and second for calculation. For example you could in the future deliver only numbers, without the string with expression.
So the idea of design:
And the example implementation: