The problem
Many times we are faced with a challenge of searching for the existence of a specific value in data collections like arrays. This can even become more complex when the array size is extremely large.
In our most recent course work at University, we were asked to develop a banking system that would allow a banker withdraw or deposit money from a customer’s account on demand. This meant that the user had to identify themselves to the banker with their account numbers, then the bankers had to validate the existence of the account number, and finally perform the required transaction.
The solution
Assuming that your bank accounts are stored in an array of strings called bank_accounts and initialized with a few values. To find out whether account number 0L2010202 exists in the array, you would use the following block of code.
String[] bank_accounts = {"0L2010201", "0L2010202", "0L2010203", "0L2010204", "0L2010205", "0L2010206"};
String account_number = "0L2010202"; // The account number to search for in the array.
int counter;
boolean account_found = false; // true = account found
for (counter = 0; counter < bank_accounts.length; counter++)
{
if (bank_accounts[counter] == account_number)
{
// The account number exists
account_found = true;
break; // Jump out of the loop.
}
}
if (account_found == true)
{
System.out.println("The account exists!");
}
else
{
System.out.println("The account was not found!");
}
We use the for loop (line 09-23) to move through all the array indexes. The if statements inside the loop (line 12 – 21) check for the equivalence the value stored in the current index to the account number we are searching for. If the two are equivalent, then the account number exists in the array. So we set our account_found boolean variable to true and we stop the loop using the break statement.
Figure 1: A screen shot of the program executing in Dr. Java