# Get a set of from String to a double stack?

• 11-23-2011, 01:18 AM
dacoolest
Get a set of from String to a double stack?
Hi, There is a string variable holding a set of values and mathematical operators. eg: "+2.5+3.2-5.2" Operators are either minus(-) or plus (+) and there is always an operator in front of each value.
they are placed to identify whether the value is negative or positive.

I want to get these values separately to a double stack.

I tried to write a function that reads the value and the sign separately and transfer them to the double stack as doubles. But I'm getting strange inputs.

Code:

```    private void getValue() {         int sign = -1;         double value = 0;         char nextCh = ' ';         String temp = " ";                 if (str.charAt(j) == '+') // get the sign         {             sign = 1;         }         else if (str.charAt(j) == '-')         {             sign = -1;         }                 j++;         temp += Character.toString(str.charAt(j));         nextCh = str.charAt(j+1);         while (nextCh != '+' && nextCh != '-' && nextCh != '*' && nextCh != '/')         {             if (j != (str.length()-2) )             {                 temp += Character.toString(nextCh);                 j++;                 nextCh = str.charAt(j+1);             }         }         System.out.println(temp);         value = Double.parseDouble(temp);         if (sign == -1)         {             value = value*-1;         }         else if (sign == 1)         {             value = value * +1;         }         st2.push(value);     }```
I'm getting values with a space infront of them.

+2.5+1.5+3.5
2.5
1.5

the index, j is being used by some other loops as well. Because of that, the j's increments has to be stopped soon before an operator sign.

and the program continues to run (stuck in a loop) or something.
• 11-23-2011, 01:54 AM
Junky
Re: Get a set of from String to a double stack?
You could use a StringTokenzer (yeah I know it is deprecated but it still has its uses) to break the String into the signs and values. Then read one token (sign) and read another token (value). Then use an if statement on the sign to determine what to do with the value. Wrap it all up in a loop.