【问题标题】:Why I can't increament in scala?为什么我不能在scala中增加?
【发布时间】:2017-09-12 22:06:45
【问题描述】:
  def guessing_game():Unit = {
    println("Welcome to the guessing game!!")

    val guess_count:Int = 0
    val answer = Random.nextInt(50)
    var guess_num = scala.io.StdIn.readLine("Input your guess number > ").toInt

    while(guess_num != answer || guess_count < 5){

 ====> guess_count += 1    //  <==============================

      var situation = if(guess_num > answer){"Your guess is higher!"}else{"Your guess is lower!"}
      println(situation)
      guess_num = scala.io.StdIn.readLine("Input your guess number > ").toInt
    }
    if(guess_num == answer){
      println("Congratulation....You win!!")
    }else{
      println("You hav run out of guess!")
    }

它说: 错误:(16, 25) 值 += 不是 Int 的成员 表达式不会转换为赋值,因为接收者不可赋值。 guess_count.toInt += 1

【问题讨论】:

    标签: scala increment


    【解决方案1】:

    guess_count 是不可变的,(val),你不能改变它。如果需要更改变量,请使用var

    【讨论】:

      【解决方案2】:

      您可以在 scala 中递增,但错误是您正在递增并将值重新分配给最终变量,这就是它抛出错误的原因,请按如下方式更改声明,然后它将起作用

      var guess_count:Int = 0

      谢谢

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-19
        • 2010-10-25
        • 2018-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多