Exercise Construction Steps (Cont.)

  1. Calling a Java Program (Java)
  2. The Java program SearchString.java lists the number of keywords matched between the string (the first command-line argument args[0]) and the query (the second command-line argument args[1])
      shell> /usr/bin/java  SearchString \ 
               'PHP Java C# MySQL' 'mysql php' 
    The class java.util.StringTokenizer allows an application to break a string into tokens.

    ~/public_html/cgi-bin/280/5/SearchString.java
    // The StringTokenizer class is to break a string into tokens. 
    import java.util.StringTokenizer;
    
    public class SearchString {
    
      // The main( ) method will be called first when program is executed.
      public static void main( String args[ ] ) {
        int count = 0;
    
        SearchString searchString = new SearchString( args[0], args[1] );
        System.out.println( "The string: " + args[0] );
        System.out.println( "The query: "  + args[1] );
    
        StringTokenizer keyword = new StringTokenizer( args[1], " " );
        // hasMoreTokens( ) tests if there are more tokens available.
        while ( keyword.hasMoreTokens( ) )
          // nextToken( ) returns the next token.
          count += searchString.keywordSearch( keyword.nextToken( ) );
        System.out.println( "Number of keywords found: " + count );
      }
    
      // Two member variables
      private String str;
      private String query;
    
      // A constructor
      public SearchString( String s, String q ) {
        str   = s;
        query = q;
      }
    
      // A member method
      public int keywordSearch( String keyword ) {
        // indexOf( ) returns the index position of the first occurrence of
        // a specified string.  -1 is returned if the string is not found.
        if ( str.toUpperCase( ).indexOf( keyword.toUpperCase( ) ) != -1 )
          return( 1 );
        else
          return( 0 );
      }
    }