Java Reference
In-Depth Information
if (found)
return loc;
else
return -1;
}
If the method seqSearch returns a value greater than or equal to 0 , it is a successful
search; otherwise, it is an unsuccessful search.
As you can see from this code, you start the search by comparing searchItem with
the first element in the list .If searchItem is equal to the first element in the
list , you exit the loop; otherwise, loc is incremented by 1 to point to the next
element in the list .Youthencompare searchItem with the next element in the
list , and so on.
You can also include the method seqSearch in the class OneDimArrayMethods just
like other methods. Suppose that you have included the method seqSearch in this
class . Example 9-7 shows how to use the method seqSearch in a program.
EXAMPLE 9-7
// This program illustrates how to use a sequential search in a
// program.
import java.util.*;
//Line 1
public class TestSeqSearch
//Line 2
9
{
//Line 3
static Scanner console = new Scanner(System.in);
//Line 4
public static void main(String[] args)
//Line 5
{
//Line 6
int [] intList = new int [10];
//Line 7
int number;
//Line 8
int index;
//Line 9
System.out.println("Line 10: Enter "
+ intList.length + " integers.");
//Line 10
for (index = 0; index < intList.length; index++) //Line 11
intList[index] = console.nextInt();
//Line 12
System.out.println();
//Line 13
System.out.print("Line 14: Enter the number "
+ "to be searched: ");
//Line 14
number
= console.nextInt();
//Line 15
System.out.println();
//Line 16
index = OneDimArrayMethods.seqSearch(intList,
intList.length, number);
//Line 17
Search WWH ::




Custom Search