Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

if statements  RSS feed

 
kelly ball
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
my college project has to be in tomorrow and I'm struggling with one aspect
have written a while loop to search through an array
when a string matches I want to stop the loop and do nothing but writing an esle clause after the if still sees the name I have found added to my list when I don't want it to?
any pointers please?

[ January 14, 2004: Message edited by: kelly ball ]
 
Igor Ko
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let use "break" to quit the cycle.

[ January 14, 2004: Message edited by: Igor Ko ]
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

First, a couple of things here. Try stepping through the logic yourself. Take a List of names {Joel, Sarah, Michael, Brian} and try adding the name "Sarah" to it. You start with index = 0, get the elemtnt at 0, find that Sarah != Joel, and so you add it to the list. See the problem? You have your members.add call happening at every step of the list. It needs to be moved outside the loop, and some sort of boolean flag to indicate whether or not it was found.
Secondly, lines 4, 5, and 8 can be combined into a for loop that does the exact same thing:

Which works just as well, unless you (or your professor) Really likes while loops.
 
kelly ball
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
joel & igor
thanks for all this - I see the error in my loop, but
please may I ask how I get a boolean var changed to (say) false and then implement an add()?
kelly still rather
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Something like this (not actual code, but pseudo-code:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!