File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General 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 » Java in General
Bookmark "Searching an Array" Watch "Searching an Array" New topic
Author

Searching an Array

Zack Lock
Greenhorn

Joined: Feb 15, 2011
Posts: 5
I need to search an array of objects to see see which object contains a string. The array is created from a txt file in the following program


When the user enters the desired account number, it should search the array for a matching aNumber(account number). Any tips on accomplishing this?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40064
    
  28
It would be easier if you put the account number and account into a Map, but that probably isn't a viable option at present. You are going to have to sort the array and do a binary search, or a linear search. The latter is easier; you simply use a for loop; I suggest you have a boolean called found or similar . . . then you can break out of the loop at the appropriate moment. Obviously I'm not giving you any more code.

A binary search is much faster than linear, except in very small arrays, but it only works if you sort the array beforehand.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40064
    
  28
By the way: why don't you override the toString() method in your account class.
If you can use a Scanner for input from the keyboard, why don't you use a Scanner for input from the text file?
You are going to have problems matching account numbers; you appear to be recording the number as a String and then searching for it as a double. I have never seen an account number which wasn't a whole number.
Zack Lock
Greenhorn

Joined: Feb 15, 2011
Posts: 5
The input as a double was just an error I have fixed since the post. I appreciate the advice, I'm not looking for someone to code for me, just point me in the right direction. I'm trying to get ahead on assignments in an advanced Java class, and I'm at the point where we haven't covered any of the topics I'm working on in lecture. I'll try an implement a linear search per your suggestion. Thanks!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Searching an Array