This program below when run does not halt. I don’t think I made a major error but please help me for I’m new in Java.
import java.util.*;
public class ReverseWords {
public static void main( String args[] ) {
String paragraph;
Scanner input = new Scanner (System.in);
System.out.print("Enter a paragraph: ");
paragraph = input.nextLine();
paragraph = paragraph.trim();
StringTokenizer tokens = new StringTokenizer(paragraph, ".");
while (tokens.hasMoreTokens()){
for (int i = paragraph.length() - 1; i>=0; i--) {
System.out.print(paragraph.charAt(i));
}
System.out.print(". ");
}
System.out.println();
}
}
When I input: The quick brown fox. Jumps over. The lazy dog.
It outputs: .god yzal ehT .revo spmuJ .xof nworb kciuq ehT. infinite times.
Thank you very much!
Look at this:
You’re never fetching the next token. So if that ever returns true, it will keep doing so forever. You probably want (in the while loop):
That’s assuming you want to reverse each partial-sentence within each line. It’s not really clear what your aim is.