I am trying to better understand the concept of Stack in java.
I am simply trying to push each element of a string onto a stack & then use the ToString method in the stack class to output the elements of the stack .
I am getting unpredictable results & looking for assistance on the reason why .
my input string is : ""10 ( 30 – 5 * 2 ) /5"
but the output I get is "[0, , (, 3, , , , , , , 5]" & I cant verify why .
the following is my code :
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
String myString= "10 ( 30 – 5 * 2 ) /5";
System.out.println(postFix(myString));
}
public static String postFix (String expression ) {
Stack<Object> myStack = new Stack<>();
String outputString = "";
CharacterIterator ct = new StringCharacterIterator(expression);
for (char c = ct.first(); c != CharacterIterator.DONE ; c = ct.next()) {
myStack.push(ct.next());
outputString = myStack.toString();
}
return outputString;
}
}
CodePudding user response:
There are two suggestions for your code.
First, please pull the "outputString = myStack.toString();" out of the for loop as there is no benefit to having it there since you are overwriting that value each time you iterate and only us the value at the very end.
Second, to fix the actual question you are asking, you need to review the documentation on characterIterator.next();. You are seeing odd results (every other item) due to this method being called twice, once in your loop condition and again in the loop body but only pushing the value of it once in the body. Please read the documentation here for more details on what .next() truly does but see this code on how you can replace your for loop:
public static String postFix (String expression ) {
Stack<Object> myStack = new Stack<>();
String outputString = "";
CharacterIterator c = new StringCharacterIterator(expression);
for(char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
myStack.push(c);
}
}
CodePudding user response:
If you are just looking to push each of the characters onto the stack then you don't really need an iterator. Just use the enhanced for loop:
for (char ch: expression.toCharArray()) {
myStack.push(ch);
}
You could also achieve the same thing with a stream instead of an iterator:
str.chars().forEach(ch -> myStack.push((char)ch));