user1531959
user1531959

Reputation:

Why does this display the output infinitely / many times?

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!

Upvotes: 0

Views: 290

Answers (3)

Christian Stieber
Christian Stieber

Reputation: 12496

I've never used Java, but unless the "StringTokenizer" is very strange: your while loop checks "hasMoreTokens", but the body of the loop never removes tokens. So it will always have more tokens...

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503954

Look at this:

 while (tokens.hasMoreTokens())

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):

String token = tokens.nextToken();
for (int i = token.length() - 1; i >= 0; i--) {
    System.out.print(token.charAt(i));
}
System.out.print(". ");

That's assuming you want to reverse each partial-sentence within each line. It's not really clear what your aim is.

Upvotes: 3

DPlusV
DPlusV

Reputation: 14356

You are never even using the tokenizer in your loop. As such, hasMoreTokens() always returns true.

Upvotes: 2

Related Questions