• Post Reply Bookmark Topic Watch Topic
  • New Topic

Finds entries in an array, sometimes.  RSS feed

 
Lonnie Wood
Greenhorn
Posts: 15
Chrome
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Posts: 55772
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!