Zamotay
Zamotay

Reputation: 11

Extracting math operator from a String[] java

Here is my code:

public static void main(String[] args) {
    args = new String[3];
    args[1]="+";
    args[0]="8";
    args[2] = "5";
    if(args.length<3){
        System.out.println("Not enough arguments");
    } else if(args[1]!="+"&&args[1]!="-"&&args[1]!="*"&&args[1]!="/"){
        System.out.println("Don't equals basic math operators.Please iput j'+', '-' ,'*', '/'");
    }else if(!args[0].matches("[0-9]+")||!args[2].matches("[0-9]+")){
        System.out.println("Error. Please insert numeric value");
    }else {
        double a = Double.parseDouble(args[0]);
        char b = args[1].charAt(0);
        double c = Double.parseDouble(args[2]);

        System.out.println(a+b+c);

    }

a+b+c gives result of 56.0 insted of expexting result of 13.Can anybody explain where is my fault? Thanks beforehand.

Upvotes: 0

Views: 405

Answers (1)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

It's because the char is a numeric type and what happens is that you're summing the value of a, the numeric value of b, and the value of c.

You have to create a new conditional statement. For example:

if (b == '-') {
    System.out.println(a - c);
} else if (b == '+') {
    System.out.println(a + c);
} else if (b == '*') {
    System.out.println(a * c);
} else if (b == '/') {
    System.out.println(a / c);
}

Also, you can take advantage of the Java Scripting API, instead of making complex conditional statements. The trick to represent the operation as a String and pass it to the ScriptEngine#eval() method.

ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
ScriptContext context = engine.getContext();
StringWriter writer = new StringWriter();
context.setWriter(writer);

engine.eval("print(" + a + b + c + ")");

String output = ;
System.out.println("Script result: " + writer.toString());

Upvotes: 1

Related Questions