Array Searching Example

The program shown at the end of this web page solves the following problem:

Write a Java main program that determines whether or not various search terms are in a list of strings. The input will come from the command line as follows:

  1. an integer, n, that represents the number of strings in the list
  2. n strings representing the strings in the list
  3. an unspecified number of strings. For each string your program should determine if the string is in the list.

Write a search method that you call from your main program to perform the actual search. It should return true/false depending on whether or not it finds the string. Its parameters should include the array of strings and the string to be found.

Your main program should allocate a new array of length n for the list of strings, store the strings in the list, and then loop through the remaining strings on the command line, call the search method, and print the result using System.out.printf. Your program should print the string and either true/false. For example, the command:

   java search 3 brad nels james jim nancy brad nels
should produce the output:
   jim false
   nancy false
   brad true
   nels true

The Program

class search { 
    public search(String args[]) {
	int n = Integer.parseInt(args[0]); // parseInt converts String to int 
	String searchList[] = new String[n]; 
	int i; 
	for (i = 0; i < n; i++) { 
	    searchList[i] = args[i+1]; 
        // %b is the formatting string for a boolean 
	for (i = n+1; i < args.length; i++) { 
	    System.out.printf("%s %b\n", args[i], find(searchList, args[i])); 

    boolean find(String list[], String key) { 
	for (String value : list) 
	    if (value.equals(key)) 
		return true; 
	return false; 

    public static void main(String args[]) { 
	new search(args);