Massassi Forums Logo

This is the static archive of the Massassi Forums. The forums are closed indefinitely. Thanks for all the memories!

You can also download Super Old Archived Message Boards from when Massassi first started.

"View" counts are as of the day the forums were archived, and will no longer increase.

ForumsDiscussion Forum → String searching in an array
String searching in an array
2007-11-28, 5:41 PM #1
In Java...

For example I have a BankAccount class which stores a bankID and balance in an object array. I have to ask the user for a name and if it matches a value stored in the array print "Found" and if no matching ID is found print "Error".

So heres my code so far:

Code:
Scanner scan = new Scanner(System.in);
System.out.println("Enter the id:");
String id = scan.next();
scan.nextLine();

for (int i=0; i<count; i++)
    {
    String temp = accts.getID();
        if (id == temp)
           System.out.println("Found");
       else
           System.out.println("Error");

    }
Problem is its not working...

2007-11-28, 5:44 PM #2
You have to compare strings using String.equals() instead of the == operator, if I recall correctly.
2007-11-28, 5:44 PM #3
if(id.equals(temp)) should be used.

Might also need to add a null check on id before performing that comparison.
2007-11-28, 5:49 PM #4
But it still prints "Found" even when I enter a String not in the array, except it prints "Error" every time its not found and loops through the array until id = temp. How can I work around (or with) this?

*Code edited

2007-11-28, 5:55 PM #5
Try this:

Code:
Scanner scan = new Scanner(System.in);
System.out.println("Enter the id:");
String id = scan.next();
scan.nextLine();

for (int i=0; i<count; i++)
    {
    String temp = accts.getID();
        if (temp.compareTo(id) == 0)
           System.out.println("Found");
       else
           System.out.println("Error");

    }


To explain: String is a class in Java; thus, when you use the == operator to compare two strings, you're doing a comparison to see if they're the same instance of the String class. With primitives such as integer, float, boolean, and char, the == comparison can be used because those are primitives, not objects.

(Though why are you using Strings when a float or int would suffice? Do you not know about the Integer.parseInt()/Double.parseDouble() methods, and how to catch NumberFormatExceptions?)
the idiot is the person who follows the idiot and your not following me your insulting me your following the path of a idiot so that makes you the idiot - LC Tusken
2007-11-28, 5:56 PM #6
Code:
boolean idFound = false;
for (int i = 0; i < count; i++)
{
    String temp = accts.getID();
        if (id.equals(temp))
        {
           idFound = true;
           break;
        }
}
if(idFound)
    System.out.println("Found");
else
    System.out.println("Error");


I'm assuming count has been set to count = accts.length.

You only want "Error" to display once, so initialize a boolean variable to false (to act as a sort of flag). If the id is found, the boolean flag is set to "true", indicating that the id was found. If not, the loop continues checking until the end of the array. If no id is found, the boolean flag remains "false".

After the loop, check the value of the flag. If "true", then it was found. Otherwise, it's an error.

The "break" you see in the code I added is strictly performance related. If the id is found early in the array, then there is no need to iterate over the remainder of the array.
2007-11-28, 6:02 PM #7
Yup that works now :)

2007-11-28, 6:04 PM #8
Assuming accts is an array of type Account, a for each loop can make things more readable.
Code:
Scanner scan = new Scanner(System.in);
System.out.println("Enter the id:");
String id = scan.next();
scan.nextLine();

bool isFound = false;
for(Account a : accts)
{
    String s = a.getID();
    if(id.equals(s))
    {
        System.out.println("Found");
        isFound = true;
        break;
    }
}

if(!isFound)
{
    System.out.println("Error");
}
Or if it's not called Account, just change it to whatever you need, of course.
Bassoon, n. A brazen instrument into which a fool blows out his brains.
2007-11-28, 6:39 PM #9
Okay one more question: Is it possible to store a variable used in a for-loop in another part of the program? For example, I want to store the index of the array at which the ID match was found and store it for later use (to retrieve the balance, etc).

2007-11-28, 6:51 PM #10
Sure, you can just use another variable like this.
Code:
int index;
for(int i = 0; i < 10; i++)
{
    // loop code
    index = i;
}

// something that uses index


Alternatively, just can define the loop variable outside of the loop first.
Code:
int i;
for(i = 0; i < 10; i++)
{
    // loop code
}

// something that uses i
Bassoon, n. A brazen instrument into which a fool blows out his brains.
2007-11-28, 7:18 PM #11
What genius at Sun Microsystems decided operator overloading was deemed "too unsafe" to it not be implemented.


Benefits > Costs
Code to the left of him, code to the right of him, code in front of him compil'd and thundered. Programm'd at with shot and $SHELL. Boldly he typed and well. Into the jaws of C. Into the mouth of PERL. Debug'd the 0x258.

↑ Up to the top!