Manivel Sundaresan Manivel Sundaresan - 4 months ago 18
Java Question

Unfitting output of String manipulation

import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Scanner;
import java.util.StringTokenizer;

public class N12 {
public String reverseWords(String s) {

String value = "";
ArrayList list = new ArrayList();
StringTokenizer st = new StringTokenizer(s);
StringBuilder sb = new StringBuilder();

while (st.hasMoreTokens()) {
list.add(st.nextToken());
}


ListIterator lt = list.listIterator();

while (lt.hasPrevious()) {
String t = (String) lt.previous();
System.out.println(t);
sb.append(t);
}
value = sb.toString();
return value;
}

public static void main(String ss[]) {
N12 sol = new N12();
Scanner scan = new Scanner(System.in);

String s1 = scan.nextLine();

System.out.println(sol.reverseWords(s1));
}


}

I want to reverse the string as word by word. I got the string and stored it using StringTokenizer. For reversing the string from last word, i have used hasPrevious() and previous() methods of ListIterator. It shows nothing. If I use hasNext() and next() instead, it's working properly.

(e.g.)
Input:

I am back

Output:

back am I

Answer

You can't use hasPreviews() because you're starting at the begining of the list. You need to start at the end. Try to use :

ListIterator lt = list.listIterator(list.size());