0

(JAVA)

Hello so I want to write a program where the input is (2+3)*(2+1) for example I want my program to return 15.

Is there a way of making the input (2+3)*(2+1) into a integer?

I know that you can write

int product = (2+3)*(2+1);

however, can I write this something like:

String input = (2+3)*(2+1); int product = input;

Obviously this does not work. But can it be done in a beautiful way without using recursive functions that call eachother?

Georg
  • 17
  • 5
  • It sounds like you want to write a calculator. There are a zillion and one example of this on the internet. You'll never be able to assign the `String` to an `int` though, but you could do something like `int product = evaluate(input);` after you implement the `evaluate(String input)` method. – lane.maxwell May 09 '23 at 20:15
  • Symbols like `+`, `*`, `(` and `)` are optimized and removed at compile time. By the time your program starts, those symbols have no meaning apart from being characters. You need to write your own function(s) to parse the string and perform operations based on the characters – Nordii May 09 '23 at 20:16
  • 1
    If you are trying to write elegant/scalable functions without recursion, I would suggest researching `infix` vs `postfix` notation. – Nordii May 09 '23 at 20:18

1 Answers1

0

You will need some kind of parser. Either build it yourself, or increase efficience and build it using https://www.antlr.org/. They even have an example like yours on their homepage.

If both options are not your taste, you might want to embedd some scriping or expression library. Examples are

Queeg
  • 7,748
  • 1
  • 16
  • 42