简体   繁体   English

Scala无限while循环,即使条件更改为false

[英]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' to '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 is an output snippet. while循环无限期运行,上面是一个输出代码段。 Why isn't the while loop exiting even though the condition is changed to false? 即使条件更改为false,为什么while循环也没有退出?

Big picture, I need to ensure that each Robot instance has a unique name --I'm open to alternatives to using a while loop. 大图,我需要确保每个Robot实例都有一个唯一的name我愿意接受使用while循环的替代方法。

Update: per Jason C, below code fixes reassignment problem: 更新:根据Jason C,以下代码修复了重新分配问题:

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 your loop: 这是因为在您的循环中:

val initName = ...
while(nameList.names.contains(initName)){
    val initName = ...
    ...
}

You redeclare val initName in the loop. 您在循环中重新声明val initName So now you effectively have two different values. 因此,现在您实际上拥有两个不同的值。 The one in the while condition is the outer scoped one. while条件是外部作用域。 The one declared in the loop has no effect on it. 在循环中声明的那个对此无效。

I don't actually know Scala but from What is the difference between a var and val definition in Scala? 我实际上并不了解Scala,但是从Scala 的var和val定义之间有什么区别? I'm guessing the solution is to change the outer one to var (so it's modifiable) and drop the val entirely from the inner one (so you're not redeclaring it). 我猜解决方案是将外部的val更改为var (这样它是可修改的),然后将val完全从内部的val删除(因此您无需重新声明)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM