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:)
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: