A Java Example


Before giving the programming exercise construction steps, typical Java program construction steps are as follows:
  1. Sign in to the server undcemcs02.und.edu .

  2. By using an editor such as emacs, write the Java program SearchString.java which counts the number of keywords in a query contained in a string.

  3. Compile it by using the following command:
      shell> /usr/bin/javac SearchString.java 
  4. Execute the compiled code with the command-line arguments:
      shell> /usr/bin/java SearchString \ 
             'PHP MySQL AJAX Java Oracle' 'java object php' 
      The string: PHP MySQL AJAX Java Oracle
      The query: java object php
      Number of keywords found: 2
    where the shell symbol \ is used to remove any special meaning for the next character read and for line continuation; i.e., continue the current command to the next line.
String =     Query =

         
http://undcemcs01.und.edu/~wen.chen.hu/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 );
  }
}




      Don’t count your chickens before they hatch.