Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Assuming that all your values are of integer type, you should create a <code>HashMap&lt;string,Integer&gt;</code> to store variable values, and pass it to your <code>evaluate</code> method:</p> <pre><code>public static void main(String[] args) { NodeList commandList = ... // get your XML from somewhere Map&lt;string,Integer&gt; vars = new HashMap&lt;string,Integer&gt;(); for (Node node : commandList) { evaluate(node, vars); } // At this point, vars contains values of all variables assigned in commands // from the command list } </code></pre> <p>The evaluation should become relatively straightforward:</p> <pre><code>private static Integer evaluate(Node node, Map&lt;string,Integer&gt; vars) { if (node is an assignment) { String varName = ... // get variable name from node Node expr = ... // get the node representing expression being assigned Integer value = evaluate(expr, vars); vars.put(varName, value); return value; } if (node is a variable reference) { String varName = ... // get variable name from node return vars.get(varName); } if (node is an integer constant) { String constVal = ... // Get the representation from XML return Integer.decode(constVal); } if (node is a binary expression) { Node lhs = ... // Get the left-hand side expression from the node Node rhs = ... // Get the right-hand side expression from the node Integer lhsVal = evaluate(lhs, vars); Integer rhsVal = evaluate(rhs, vars); if (operator is plus) { return new Integer(((int)lhsVal) + ((int)rhsVal)); } if (operator is minus) { return new Integer(((int)lhsVal) - ((int)rhsVal)); } if (operator is multiply) { return new Integer(((int)lhsVal) * ((int)rhsVal)); } if (operator is divide) { return new Integer(((int)lhsVal) / ((int)rhsVal)); } // ... and so on } // ... and so on } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload