Scala infinite while loop even though condition changed to false -
import scala.collection.mutable.arraybuffer object namelist { val names = arraybuffer("placeholder") } class robot { val r = scala.util.random val letters = 'a' 'z' val name = { val initname = namelist.names(0) while(namelist.names.contains(initname)){ val initname = letters(r.nextint(26)).tostring + letters(r.nextint(26)).tostring + r.nextint(10).tostring + r.nextint(10).tostring + r.nextint(10).tostring println("while", initname) println("while", namelist.names) println("checker", namelist.names.contains(initname)) } println("outside", namelist.names) namelist.names += initname initname } } outputs
(while,la079) (while,arraybuffer(placeholder)) (checker,false) (while,io176) (while,arraybuffer(placeholder)) (checker,false) the while loop runs indefinitely, above output snippet. why isn't while loop exiting though condition changed false?
big picture, need ensure each robot instance has unique name--i'm open alternatives using while loop.
update: per jason c, below code fixes reassignment problem:
var initname = namelist.names(0) while(namelist.names.contains(initname) == true){ initname = letters(r.nextint(26)).tostring + letters(r.nextint(26)).tostring + r.nextint(10).tostring + r.nextint(10).tostring + r.nextint(10).tostring
it's because in loop:
val initname = ... while(namelist.names.contains(initname)){ val initname = ... ... } you redeclare val initname in loop. have 2 different values. 1 in while condition outer scoped one. 1 declared in loop has no effect on it.
i don't know scala what difference between var , val definition in scala? i'm guessing solution change outer 1 var (so it's modifiable) , drop val entirely inner 1 (so you're not redeclaring it).
Comments
Post a Comment