I am working on this exercise:

Write an application that asks its user to type a complete sentence on one line.
The application then displays in the console window the words in the sentence,
one word per line, less any punctuation.

I have the following code:

import javax.swing.*;
   import java.util.*;

   public class Tokens{
   
      public static void main(String[] args){
      
         String input = JOptionPane.showInputDialog("Give a complete sentence");
      
         boolean processing = true;
         StringTokenizer x = new StringTokenizer(input, "., ?!" );
         while(processing){
         
            System.out.println(x.nextToken());
            if(input == ""){
               processing = false;
            }

         }

      }
   
   }

the while-loop is run one time too many, and as a result I get a noSuchElementException error. I know that my variable input remains the same as I give it initially, so I know my 'if(input == "")' statement always returns false. I need to know if there is any ready to use method to know that all tokens have been generated that I can use instead of my if statement, or should I just build me one?

possible solution:

while(x.hasMoreTokens()){     
    System.out.println(x.nextToken());		
}

do you need to use a boolean variable? i don't see why you would

thank you jimaat7. that worked perfectly fine.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.