Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Searching an array?

 
Katie Tuffrey
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 208
9
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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.
 
D. Ogranos
Ranch Hand
Posts: 214
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic