Ignoring Spaces

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

A good answer might be:

C:/> java TokenTester
Enter a string: val = 12+8
val

=

12
+
8

Ignoring Spaces

Notice that the spaces are returned as well as the other delimiters and tokens. This might not be quite what you want. You might like to ignore spaces completely and use only "=+-" as delimiters. The following does that:

import java.io.*;
import java.util.*;

public class TokenTester
{
  public static void main ( String[] args ) throws IOException
  {
    BufferedReader stdin = 
      new BufferedReader(new InputStreamReader(System.in));

    System.out.print("Enter a string:");
    String data = stdin.readLine();   
    
    StringTokenizer tok = 
      new StringTokenizer( data, "=+-", true ); // NO space before =

    while ( tok.hasMoreTokens() )
      System.out.println( tok.nextToken().trim() );
  }
}

Now nextToken() returns the Strings "val ", "=", " 12", "+", and "8". The trim() method trims spaces off both ends of these Strings.

QUESTION 19:

A String, time, contains a time, such as "9:23AM" or "12:45PM". Say that you want to extract hours, minutes, and AM or PM from the string. Do this with StringTokenizer.