3

I want to parse an operator say "+" from the string "+" which i entered as command-line argument at run-time and then add two integers say 'a' and 'b'.

So how can i perform the above task?

Himanshu Aggarwal
  • 1,763
  • 1
  • 23
  • 35

3 Answers3

2

If you are using Java 1.7, you can use a switch to test for each possible operator and then do the corresponding operation:

switch(operator){
    case("+"): result = a + b; break;
    case("-"): result = a - b; break;
}

For older versions of Java can be done using if statements.

niculare
  • 3,569
  • 1
  • 23
  • 36
2

What nobody so far is telling you is that to recognize arithmetic expressions in general you need to use, or write, a parser. Have a look for the Shunting-yard algorithm, recursive descent expression parsing, etc.

user207421
  • 298,294
  • 41
  • 291
  • 462
1
if (string.equals("+")) {
    System.out.println("The result is " + (a + b));
}
JB Nizet
  • 657,433
  • 87
  • 1,179
  • 1,226