Manivel Sundaresan Manivel Sundaresan - 9 months ago 74
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()) {

ListIterator lt = list.listIterator();

while (lt.hasPrevious()) {
String t = (String) lt.previous();
value = sb.toString();
return value;

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

String s1 = scan.nextLine();



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.


I am back


back am I


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());