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?

2
  • What is the grammar? You need that before parsing. Commented Mar 3, 2013 at 8:49
  • 1
    if say i enter "10+20" in commandline then how can i get the answer as "30"? Commented Mar 3, 2013 at 9:03

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

ok. i would hav to explore it a little more than.
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.

4 Comments

Or operator.charAt(0)
if say i enter "10+20" in commandline then how can i get the answer as "30"?
That's another question. Why didn't you ask that?
i thought to try it later on if i could get some hint on this one.
1
if (string.equals("+")) {
    System.out.println("The result is " + (a + b));
}

1 Comment

if say i enter "10+20" in commandline then how can i get the answer as "30"?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.