Searches
Now that we have an understanding of loops and arrays we can begin to use java to search through and sort data. The program below will search through an array of strings for a given element. The element is entered as a command line parameter.
Copy the following code into a
text editor and
save it as search.java.
class search {
public static void main (String args[]){
String[] names =
{ "Harry","John","Alex","Blake","Scott"};
int x;
String item = args[0];
System.out.println
("Searching for "+ item);
for (x=0 ; x < names.length ; x++)
{
System.out.println
("name "+names[x]+" at location "+x);
if (item.equals(names[x]))
System.out.println
("found "+names[x]+" at location "+x);
}
}
}
|
Line 3 sets up an array of strings and places the names "Harry", "John", "Alex", "Blake", "Scott" in the new array. The 'item' variable holds the first command line argument args[0] The for loop covers all array indices from 0 to the length of the names array Every element is printed and if a name is found, the element is printed once again with the 'found at ' prompt. Notice the item.equals method of comparing the two strings. You can't simply use the = or == to determine if the strings are identical. |
After compiling this program run it by typing
java search <parameter>
This program needs a name as a command line parameter. It will then search through the array for the name.
If one were to enter
java search Blake
The output should resemble the following.
Searching for Blake name Harry at location 0 name John at location 1 name Alex at location 2 name Blake at location 3 found Blake at location 3 name Scott at location 4
The search is case sensitive. (Notice that the name starts with an upper case letter.) The command line parameter must match the element exactly or it will not be found.
The next section will demonstrate a bubble sort in Java.
Go to the next topic: Accessing Files