File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Searching an array? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Searching an array?" Watch "Searching an array?" New topic

Searching an array?

Katie Tuffrey

Joined: Dec 14, 2011
Posts: 6
i want to search what is stored in this array:

i have this:

which does not work!!!
any tips?
i want to search for say student name and get the student profile to display.
Tina Smith
Ranch Hand

Joined: Jul 21, 2011
Posts: 208

What are you seeing when you run this code, and what do you expect to see?

You may want to try writing out a step-by-step of the above code... you get the name of the person you're searching for but never use it, students is not declared, you're comparing a textbox to an integer and expecting them to somehow be equal, and you're trying to acess into an...array?...list?...of your iterator?

On line 8 of your code, you declare an integer that looks like it's going to be used to iterate and fill up an array...but you don't do any looping; i will always be zero.

Also, static (line 26-35 of your code) means that a variable belongs to the class; there will never be more than one of each of these variables. Therefore if I declared two Students and gave them different values, they'd both come out with the same ones, which I doubt is what you expect.

Everything is theoretically impossible, until it is done. ~Robert A. Heinlein
D. Ogranos
Ranch Hand

Joined: Feb 02, 2009
Posts: 214
It looks like you're mixing your data class (for a single student) with the array containing the student data. Don't do that. Turn your class Students into Student (single!), so each instance of the class holds data about a student. Also make sure that the fields in your student class are not static, else the values will be the same for each student!

The data class should look something like this:

Then you have another class, in which you have an array (or preferably, an ArrayList) of Student objects. This would be declared something like

I added a little method to show you how to search an array of Student objects. As you see, you need to test each entry if it actually holds a Student or if it is null. This can be avoided if you use an ArrayList instead. ArrayList works with an array internally but adapts the array size so you don't need to worry about how many Students you actually enter into it:

Hope this helps.
I agree. Here's the link:
subject: Searching an array?
It's not a secret anymore!