Searching an Array
posted 14 years ago
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
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?
When the user enters the desired account number, it should search the array for a matching aNumber(account number). Any tips on accomplishing this?
posted 14 years ago
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
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.
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
Marshal
Posts: 81615
593
posted 14 years ago
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
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.
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
Posts: 5
posted 14 years ago
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
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!
| She said she got a brazillian. I think owning people is wrong. That is how I learned ... tiny ad: The new gardening playing cards kickstarter is now live! https://www.kickstarter.com/projects/paulwheaton/garden-cards |






