This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
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: 32694
4
posted
0
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: 32694
4
posted
0
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
posted
0
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://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.