0

I have a program I need to write and was wondering if anyone could give me some pointers. I have written the a lot of the program but need hints on an algorithm because I'm stuck. I am using Java.

I had thought of traversing the file, storing the instruction and number in a 2D array. The array ends when I reach 'Apply'. Does tat sound like a good idea?

Write some code to calculate a result from a set of instructions. Instructions comprise of a keyword and a number that are separated by a space per line. Instructions are loaded from file and results are output to the screen. Any number of Instructions can be specified. Instructions can be any binary operators of your choice (e.g., add, divide, subtract, multiply etc). The instructions will ignore mathematical precedence. The last instruction should be “apply” and a number (e.g., “apply 3”). The calculator is then initialised with that number and the previous instructions are applied to that number.

Example:

[Input from file]
add 2
multiply 3
apply 3

[Output to screen]
15

[Explanation]
(3 + 2) * 3 = 15

4

1 回答 1

0

Rather than using an array, you know that you will have a series of operations of a known type followed by numbers of a known type. So you really want to tokenise it into your own structure that can be created from an operation name and a quantity and then knows how to perform that operation and also how to describe it. Then you can create a file parser which reads each row and returns an operation object relevant to it. You probably use an interface for that, so that your IMathmaticalOperation would have a name, symbol, number, and performOperation( number ) members and then you could have AdditionOperation, SubtractionOperation and so on that implement it and know how to perform their own operations. This also means if you decided to add new functions to your calculator it would be easy to create new objects implementing that interface without having to change your core code too much. Your file parser can then return an array of IMathmaticalOperations and doesn't have to know the details of how they actually do things, just that they implement the operations correctly.

It also makes it easy to unit test. It sounds like you're just starting out, so learning how to do unit testing now will get you on a good path for the rest of your programming life.

于 2012-06-01T09:39:42.253 回答