/************************************************** Joe owns lots of CDs. When he goes shopping, he frequently buys a new CD. He owns so many that he sometimes buys a second copy of a CD that he already owns. He wants to have a program that keeps track of all his CDs, and then he can easily check whether he already owns a title. After buying a new CD, he must add it to the TITLES array. ***************************************************/ public class CDlist { String[] titles = {"Cafe del Mar 18", "Valtari", "Nature One", "Swagg", "Netsky 2", "DJ Kicks", "Trouble" }; public CDlist() { String name = ""; do { name = input("Type the name of the CD"); search(name); } while(name.length() > 0); // type nothing to quit } void search(String name) { for(int c = 0; c < titles.length; c=c+1) { if( titles[c].equals(name) ) { output("Found " + name); return; // quits if name is found } } output("Not found - you don't own that"); } public static void main(String[] args) { new CDlist(); } public String input(String prompt) { return javax.swing.JOptionPane.showInputDialog(null,prompt); } public void output(String message) { javax.swing.JOptionPane.showMessageDialog(null,message); } } |
Type the name of the
CD [Swagg] Found Swagg ------ Type the name of the CD [Netsky] Not found - you don't own that |
This program has a list of CD titles stored in the TITLES array.
The titles are written into the array by enclosing a list
in {curly braces}. The user types the name of a CD and the program
searches for that name in the TITLES array.
The searching commands are contained in the search
method. A loop counts through all the names in the list,
starting at position 0 and ending at position titles.length
- 1 .
At each position in the array, the program checks whether the requested
name matches the title in the list:
if(
titles[c].equals(name) )
If name matches titles[c], then the program prints "found". Then
the return command ends the
search method
and execution returns to the main setup method.
If the name is not found in the list, then the loop ends and the program
displays "not found".
This algorithm is called a sequential
search (or a linear search).
This is a very common feature of programs
that contain lists of data.