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,803
  • 2
  • 24
  • 36

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,629
  • 1
  • 25
  • 39
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
  • 305,947
  • 44
  • 307
  • 483
1
if (string.equals("+")) {
    System.out.println("The result is " + (a + b));
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255