Results 1 to 2 of 2
- 11-23-2011, 12:18 AM #1
Member
- Join Date
- Nov 2011
- Posts
- 13
- Rep Power
- 0
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.
I'm getting values with a space infront of them.Java 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); }
+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.Last edited by dacoolest; 11-23-2011 at 12:30 AM.
- 11-23-2011, 12:54 AM #2
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.
Similar Threads
-
foreach loop on ArrayList<Stack<String>>
By Ciwan in forum New To JavaReplies: 21Last Post: 06-27-2011, 07:29 PM -
Stack to an ArrayList<String>
By Ciwan in forum New To JavaReplies: 5Last Post: 05-22-2011, 08:00 PM -
Stack (collection) to int via String
By aborgeld in forum New To JavaReplies: 7Last Post: 04-07-2011, 05:16 PM -
String to double HELP please!
By zhen1337 in forum New To JavaReplies: 33Last Post: 02-08-2011, 09:30 AM -
Convert from string to double
By Lord ice in forum New To JavaReplies: 4Last Post: 12-12-2010, 05:27 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks