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?
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?
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.
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.
if (string.equals("+")) {
System.out.println("The result is " + (a + b));
}