Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
Hi everyone,

I have this simple calculator here. At the moment, it only accepts two integers and an operator. I want to accept more than two integers (infinite). Keep in mind I am not looking for order of operations, just left to right. I thought about recursion, but not sure how to go about it.

Java
import java.util.Scanner;


public class Calc24 {
	    public static void main(String[] args) {
	        try (Scanner scanner = new Scanner(System.in)) {
	            System.out.println("Enter an expression of the form 3 m 5");
	            int n1 = scanner.nextInt();
	            String operation = scanner.next();
	            int n2 = scanner.nextInt();

	            switch (operation)  {
	            case "a":
	                System.out.println("Your answer is " + (n1 + n2));
	                break;

	            case "s":
	                System.out.println("Your answer is " + (n1 - n2));
	                break;

	            case "d":
	                System.out.println("Your answer is " + (n1 / n2));
	                break;

	            case "m":
	                System.out.println("Your asnwer is " + (n1 * n2));
	                break;

	            default:
	                System.out.println("Je ne sais pas");

	            }
	        }
	    }
	}
Posted
Comments
ZurdoDev 11-Mar-15 17:01pm    
What is your question?

1 solution

For the operations you have in your sample it is just a matter of reading the items in order eg:
17 + 3 - 11 * 44 / 6

Read first three items (operand1 operation operand2)
Do the calculation and save the answer as the new operand1.
Get the next two items (operation operand2)
Do that calculation and save the answer as the new operand1.
Repeat until no more items.

Once you have implemented and understood that then you can think about using operator precedence, parentheses etc.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900