W
W
Wolfbethowen2019-03-26 23:48:00
Java
Wolfbethowen, 2019-03-26 23:48:00

How to convert char to operator?

Hey! the question is elementary, but not for me:
we have:
int a = 1;
int b = 1;
char c = '+';
how to make it work System.out.print(a + c + b) is math correct (1 + 1 = 2)
and is it possible to assign variable " acb " like 1 + 1 = 2?????
I hope you understand me....

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Cheremisin, 2019-03-27
@leahch

Alas, it’s not so easy to do this in Java, there is no operator overloading in Java. You need to write your own parser and interpreter.
But! The easiest option is to use scripts or classes in the groovy language, since it is very friendly with Java. The interpreter and parser is already written for you. Download groovy, connect the jar to your project, and you're good to go.

import groovy.util.Eval
....
assert Eval.me('33*3') == 99
assert Eval.me('"foo".toUpperCase()') == 'FOO'

groovy-lang.org/integrating.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question