Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Searching an Array

 
Zack Lock
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic