Lists & Iterators
- As another example of iterator on a "virtual" collection,
StringTokenizer
can be used to get the list of words into a string:
StringTokenizer tok = new StringTokenizer("I love Java."," .");
while (tok.hasMoreTokens())
System.out.println( tok.nextToken() ); // ["I","love","Java"]
As an application, the next code implements a simple calculator:
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
StringTokenizer tok = new StringTokenizer("1 2 + 3 *");
int v1,v2;
while(tok.hasMoreTokens()) {
String val = tok.nextToken();
switch (val) {
case "+":
v1 = stack.pop();
v2 = stack.pop();
stack.push(v1+v2);
break;
case "*":
v1 = stack.pop();
v2 = stack.pop();
stack.push(v1*v2);
break;
default: stack.push(Integer.parseInt(val));
}
}
System.out.println(stack);
}
source
7 - 13Java jva jav laurent thiry uha enseignant ensisa ecole school national alsace programmation objet approche mulhouse france java object programming oriented
Java jva jav laurent thiry uha enseignant ensisa ecole school national alsace programmation objet approche mulhouse france java object programming oriented
Java jva jav laurent thiry uha enseignant ensisa ecole school national alsace programmation objet approche mulhouse france java object programming oriented
Java jva jav laurent thiry uha enseignant ensisa ecole school national alsace programmation objet approche mulhouse france java object programming oriented
Java jva jav laurent thiry uha enseignant ensisa ecole school national alsace programmation objet approche mulhouse france java object programming oriented
Java jva jav laurent thiry uha enseignant ensisa ecole school national alsace programmation objet approche mulhouse france java object programming oriented
Java jva jav laurent thiry uha enseignant ensisa ecole school national alsace programmation objet approche mulhouse france java object programming oriented
Java jva jav laurent thiry uha enseignant ensisa ecole school national alsace programmation objet approche mulhouse france java object programming oriented
Java jva jav laurent thiry uha enseignant ensisa ecole school national alsace programmation objet approche mulhouse france java object programming oriented
Java jva jav laurent thiry uha enseignant ensisa ecole school national alsace programmation objet approche mulhouse france java object programming oriented
Java jva jav laurent thiry uha enseignant ensisa ecole school national alsace programmation objet approche mulhouse france java object programming oriented