1

I need to get some input from user in my application, and then use it in Java. But, it is quite more complicated than get some value from GUI and assign it to variable. The value should be processed according some rules.

For example: input from user is string "2 + 3", then he clicks "RUN" button, and when the button is clicked I need to assign "2" to one variable, "3" to next variable, and then make SUM of it.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
John
  • 503
  • 2
  • 10
  • 25
  • Do you want to make a desktop calculator, or a java compiler? – ObscureRobot Oct 30 '11 at 07:11
  • let's imagine I want to make calculator, that will work like this: – John Oct 30 '11 at 07:12
  • I would have notepad, write "2+3+4", then click some added button, and sum will appear in some added text container. – John Oct 30 '11 at 07:14
  • I do not need to do a desktop calculator. I need to have some way how to assign some values or make some actions with instances by text interface. – John Nov 01 '11 at 02:37

4 Answers4

2

I suggest you use http://www.beanshell.org/ This tool is used in a number of IDEs with the debugger to evaluate expressions.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

Use the ScriptEngine. E.G. here.

=

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1

If all you needed is to make some simple math calculation like these, I would use 2 Stacks to maintain the syntax. You can tokenise the input Strings and then use one Stack as the operators Stack and the other as the value Stack. And then you know that for every one pop from the operator Stack, the next pop from the value Stack must be an integer. If it isn't, you know the rules is broken and you can throw an error to your user.

Carven
  • 14,988
  • 29
  • 118
  • 161
0

Here is some code for a four-function calculator.

ObscureRobot
  • 7,306
  • 2
  • 27
  • 36