reversing words of a string using stacks
i have succeeded in tokenizing and reversing the individual words using stacks but each word is a mirror of itself. how do i change it
i want "electrical engineering department " to be "department engineering electrical"
here goes my code
import java.util.StringTokenizer;
import java.util.Scanner;
import java.util.Stack;
public class ReverseWords{
public static void main (String args[]){
Scanner scan = new Scanner(System.in);
String original = scan.nextLine();
StringTokenizer string = new StringTokenizer(original);
Stack<Character> charStack = new Stack<Character>();
while (string.hasMoreTokens()){
String temp = string.nextToken();
for (int i = 0; i < temp.length(); i ++){
charStack.push(temp.charAt(i));
}
charStack.push(' ');
}
StringBuilder result = new StringBuilder();
while(!charStack.empty()){
result.append(charStack.pop());
}
System.out.println(result.toString());
}
}
Re: reversing words of a string using stacks
Why not have a stack of Strings and push scan.nextLine() to it?