Note that there are some explanatory texts on larger screens.

plurals
  1. POSplit a mathematical expression while handling negative numbers with Java
    text
    copied!<p>I'm working on an expression calculator in Java. I decided to first write a code for conversion to postfix and then write an reverse polish notation calculator. So far my calculator works great and can handle any expression including operators <code>+ - * / %</code>.</p> <p>The problem I'm having however is that it splits the expression using a space <code>input.split(" ")</code> so this means the expression must be entered <code>( 4 + ( 2 * ( -2 - 1 ) ) ) * 1.5</code> when I it should be able to be entered <code>(4+(2*(-2-1)))*1.5</code>.</p> <p>After hours of tinkering and I now know it cant work regex but would it be able to write a for loop that loops through two tokens of the string at a time and if they both equal an operator then you can assume that the second must be a negative value. Or if the Equation starts with an operator then it must be a negative value? Iterate through the string like this until the second operator gets to the end of the expression?</p> <p>Here is some code I have been playing with trying to make a start at this but since I'm still quite new to programming I can't seem to get it to work.</p> <pre><code>String expression = "(4+(2*(-2--16)))*-1.5"; ArrayList&lt;String&gt; tokens = new ArrayList&lt;String&gt;(); String orig = null; String regex = "[-+/*()]+"; String first = Character.toString(expression.charAt(0)); tokens.add(first); for (int i = 0; i &lt; expression.length(); i++) { char x = expression.charAt(i); String a = Character.toString(x); if (i &gt;= 1){ //Check i is greater than or equal to 1 char y = expression.charAt(i-1); String b = Character.toString(y); if(b.matches(regex) &amp;&amp; x == '-'){ orig = a; }else if(orig != null &amp;&amp; orig.equals("-")){ System.out.println(orig + a); tokens.add(orig + a); orig = null; }else{ tokens.add(a); } } } for(String t:tokens){ System.out.print(t+" "); } </code></pre> <p>Thanks for any help, Ciaran.</p> <p>Edit:</p> <p>My question is how can I write a method to split a mathematical expression which while splitting can tell the difference '-' as a binary operator and '-' as a unary operator? Am I on the right lines with the idea of iterating through a string and comparing the two tokens? – Ciaran Ashton 6 mins ago </p> <p>What I am trying to achieve I want to turn <code>String expression = (4+(2*(-2-1)))</code> into <code>String[] expression = (, 4, (, 2, *, (, -2, -, 1, ), ), )</code></p>
 

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