// File: SearchTester.java // The SearchDataList class shows the "linear search." The search() method // has one parameter -- an int -- and returns the index (i.e., position) of // that int in an ArrayList. If the int is not in the list, -1 is returned. import java.util.* ; // for ArrayList, Random, Scanner /** * A class to demonstrate the linear search */ class SearchDataList { //instance var's private ArrayList list ; /** * Creates an empty list */ public SearchDataList() { list = new ArrayList() ; } /** * Adds an integer score to the list. * @param score the score to be added to the list */ public void add(int score) { list.add(score) ; // calls ArrayList add method } /** * Search the list for a particular score. * @param target the score to search for * @return the index (i.e., position) of the score in the list if the score * is found; otherwise (if the score is not on the list), -1 is returned */ public int search(int target) { // examine each element in turn... for (int index = 0 ; index < list.size() ; index++) { if ( list.get(index) == target ) // found it! { return index ; // return position } } // here if not found on list...return -1 return -1 ; } /** * Return a string containing all the scores on the list. * @return the string containing all the scores */ public String toString() { String out = "" ; for (int i = 0 ; i < list.size() ; i++ ) { out += list.get(i) + " " ; } return out ; } } /** * Tests the SearchDataList class */ public class SearchTester { public static void main (String[] args) { SearchDataList data = new SearchDataList() ; Random generator = new Random() ; Scanner input = new Scanner(System.in) ; // append 10 random 2-digit ints to the list for (int i = 1 ; i <= 10 ; i++) { int num = generator.nextInt(90) + 10 ; data.add(num) ; } // print the list System.out.println("The list: " + data.toString() + "\n") ; // do some searches System.out.print("Enter int to search for " + "(or ^Z on a line by itself to quit): ") ; while ( input.hasNext() ) { int target = input.nextInt() ; System.out.println() ; // call search method int position = data.search(target) ; if ( position >= 0 ) // if found... { System.out.println( target + " found in element " + position ) ; } else // not found { System.out.println( target + " is not on the list" ) ; } System.out.print("\nEnter next int to search for " + "(or ^Z on a line by itself to quit): ") ; } } } /* sample output The list: 60 68 23 25 89 95 38 70 96 42 Enter int to search for (or ^Z on a line by itself to quit): 60 60 found in element 0 Enter next int to search for (or ^Z on a line by itself to quit): 42 42 found in element 9 Enter next int to search for (or ^Z on a line by itself to quit): 37 37 is not on the list Enter next int to search for (or ^Z on a line by itself to quit): ^Z Press any key to continue... */