10. Calculator

Making a calculator program

Let's make a program that takes two numbers and an operator and computes the answer. It should work like this:

$ java Calculator
Enter a number: 
a
Please enter a valid number:
4
Enter another number: 
2
Enter an operator (+, -, *, /): 
999
Please enter a valid operator:
+

Result: 4 + 2 = 6

As in the example above, your program should only accept valid inputs for numbers and operators. It should also work with decimal numbers:

$ java Calculator
Enter a number: 
10
Enter another number: 
3
Enter an operator (+, -, *, /): 
/

Result: 10.0 / 3.0 = 3.3333333333333335

When you've done this, make your program limit the number of decimals printed. So instead of printing 3.3333333333333335, your program would print 3.33.

If you make your program work with decimals, you'll probably find that it'll print integers like decimals, like how 10 got printed as 10.0 in the above example. See if you can make your program only print decimals if there are any, so 10 would be printed as 10 but 10.23 would be printed as 10.23.

Code in parts

Write your program in stages. Don't try to get everything working all at once. When I coded this program, I built it up like this:

Code a little. Test a lot. Then code a little more. Always think about what you're doing. It's tiring, but ultimately more efficient.

Solution

When you have a finished program or you've made a solid attempt, you can see my solution. Don't click that link unless you've really given it a good try! You can't just learn coding by reading code - you have to actually code.