Withhelds
Withhelds

Reputation: 197

Can I use a char to do calculation in Java

Is it possible for me to do something like the following below in order to save time from doing if else statement?

int x = 1;
int y = 2;
char z = '+';

System.out.println(x + z + y); //e.g. 1 + 2 i.e. 3

Please advise.

Upvotes: 0

Views: 3039

Answers (4)

acdcjunior
acdcjunior

Reputation: 135822

You can't. In your expression, the '+' char is converted to its int value. (The result of that expression would be 46: 1 + 43 + 2).

You'd have to use an if (or switch) statement:

int x = 1;
int y = 2;
char z = '+';

if (z == '+') System.out.println(x + y);
else if (z == '-') System.out.println(x - y);
// else if (z == '*') ... and so on

If you are only interested in the result, you can evaluate the String directly using Java's JavaScript ScriptEngine:

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
public class Eval {
    public static void main(String[] args) throws Exception {
        ScriptEngineManager s = new ScriptEngineManager();
        ScriptEngine engine = s.getEngineByName("JavaScript");

        int x = 1;
        int y = 2;
        char z = '+';

        String exp = "" + x + z + y;
        System.out.println(engine.eval(exp));
    }    
}

Output:

3.0

Note: there can be some issues with the use of ScriptEngine. So do not allow the user to enter the expression to be evaluated directly. Using with variables (x, y and z like you do) takes care of this problem, though.

Upvotes: 4

JNL
JNL

Reputation: 4713

The output should be 1 + 2 + 43 = 46

For char, it will take the Ascii value of '+'

Upvotes: 0

Taylor
Taylor

Reputation: 4086

That will compile but not run in the way you expect.

z will be converted to an int, which will be that character's value in the default charset (most likely ASCII).

As an example, on my computer that results in "46"

Upvotes: 0

Tim S.
Tim S.

Reputation: 56566

No, that wouldn't work as expected. (it will compile and run, but since the unicode value of + is 0x2B, or 43, and a char is treated like a number in this case, your expression x + z + y evaluates to 1 + 43 + 2, so it prints 46) You can use if/else or switch statements to evaluate what operation to do, which would work for simple inputs, or you can look at a more general expression parsing library, e.g. exp4j or jexel.

Upvotes: 3

Related Questions