Question

I have two ArrayLists

[+, / , - ]
[12,8,5, 4]

My code:

        for(int i=0; i<ops.length; i++){
            String op = setOps.get(i);

            double numer1 = Double.parseDouble(setNumbers.get(i));
            double numer2 = Double.parseDouble(setNumbers.get(i+1));

            System.out.println(numer1+op+numer2);
        }

My output:

12.0+8.0
8.0/5.0
5.0-4.0

I am able to attach the operators to the numbers, but they won't evaluate.

Était-ce utile?

La solution

It will not work that way. You need to make the operator do its thing with your own code.

Example:

if(op.equals("+") ) {
    double result = numer1 + numer2;
}

System.out.println(result);

Autres conseils

With java 8 you can use nashorn

import javax.script.*;

public class Calculate {

    public static void main(String[] args) throws ScriptException {
        String command = "1 / 2";
        ScriptEngineManager scriptManager = new ScriptEngineManager();
        ScriptEngine scriptEngine = scriptManager.getEngineByName("nashorn");
        Object result = scriptEngine.eval(command);
        System.out.println("result " + result);
    }

}

In your cases (math operations) result could be an Integer or a double. But it could be something else in other cases.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top