-1

I'm working on making a calculator on java, similar to the calculator have on our computers. I am stuck with trying to replicate this situation.

Computer Calculator:

5 / 2 = 2.5 * 2 = 5

so basically..

int/int = double * int = int 

how does that work? lol, the closest thing I can do to that is:

int num_1 = 5;
int num_2 = 2;
double ans = (double) num_1/num_2;

double num_1 = ans;
int num_2 = 2;
int ans = num_1*num_2;

But I cannot re-declare the variable names so how do i program that...haha

In case this helps, I have 3 variables in my program:

int currentValue // value displayed when number key is pressed *** eg: 2, 3, etc
int runningValue // value of running total *** eg: 2 + 2 + (right now a runningValue of 4 is shown on the computer calculator)
int finalValue // value given when the equal sign is pressed 5 + 5 = 10

help?

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680

3 Answers3

1

Since calculators work with floating point anyways, it is simplest to just use double for everything.

If you want arbitrary precision and you are in Java, you can use BigDecimal.

merlin2011
  • 71,677
  • 44
  • 195
  • 329
1

Don't convert the data type. See luser droog's answer. Use some algorithms as those suggested there. Then just keep getting the user input and keep evaluating (say into a double intermediate result variable). At the end, just format the value of that double intermediate result variable (which is now a final result) in a clever way, based on whether it has any digits after the decimal point or not.

See also:

DecimalFormat

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
0

If you want to evaluate algebraic expressions that come from user input, I very much recommend you study The Shunting-Yard Algorithm and the Stack abstract data type. Your expressions will not translate directly to the C or Java syntax, but will enter as a string or a text-stream. Then using stacks and the algorithm, you will evaluate the expression without creating "variables" for everything. At the top level, the only variables you'll need are the two stacks and the input expression.

And, as merlin2011 says, you can probably skip all the type analysis. It's overkill for this type of application. Just use a consistent type for all intermediates and results.

For inspiration, take a look at the answers to this question. Also, here's an evaluator in Java that uses recursion to save intermediate results on the call stack rather than allocate a stack datatype. (Ignore my answer that question, it's totally different from the others.)

Community
  • 1
  • 1
luser droog
  • 18,988
  • 3
  • 53
  • 105