aspose file tools
The moose likes Beginning Java and the fly likes Finds entries in an array, sometimes. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Finds entries in an array, sometimes." Watch "Finds entries in an array, sometimes." New topic
Author

Finds entries in an array, sometimes.

Lonnie Wood
Greenhorn

Joined: Feb 16, 2011
Posts: 15

Wanted to see if anyone had an idea on why my code will sometimes find what I need and sometimes it won't.

Setup.
I have an Array name accounts, contains three fields: name, StudentID, and balance. I'm asking the user for the StudentID they'd like to delete, then I'm validating it before sending it to the deleteStudentID method. The problem is that sometimes this works just fine. Other times I type in a valid ID and I get the invalid entry message. If I sit and type the studentID over and over, it will eventually find it, and move to the deleteStudentID method.

Here's the code I'm using to validate the user's input.

Any ideas on why this would be intermittent?

Thanks.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 3795
    
    1

The logic looks wrong to me there. It looks like you're iterating across all the accounts, and showing the invalid message as soon as you find an account that doesn't match it.

Whereas what you probably want to do is iterate across all the accounts, and show the invalid message if none of them match your input.

Incidentally, this would all be easier if accounts was a map of student ID to Account object rather than a list (although there may be other reasons why a list is more appropriate).
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32708
    
    4
You are probably doing a linear search in several of those cases. In which case you would want a linearSearch method, to be called in several places.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Finds entries in an array, sometimes.
 
Similar Threads
Removing an element
Polymorphism and HashMap problem
indexOf() error
A little help with a null pointer exception
How do you add objects to arrays?