【问题标题】:Scala-Cannot decrement the for loopScala-不能减少 for 循环
【发布时间】:2017-09-19 15:42:54
【问题描述】:
  def start(digit:Int)
  {
    var max = "9"*digit.toInt
    var min = "1"+"0"*(digit-1).toInt

    for(i <- max to min by -1){
                 . . ^ (type mismatch; found : String required: scala.collection.generic.CanBuildFrom[Nothing,Char,?])


      var front = i
    }



  }

它说类型“不匹配;found:Stringrequired:scala.collection.generic.CanBuildFrom[Nothing,Char,?]”

【问题讨论】:

  • max 和 min 都是字符串,你的意思是它们是 Ints 吗?
  • 是的,我将其转换为 Int。
  • 一旦你把它们变成整数,它就可以工作了
  • 好的..我会尝试其他的。
  • 为了语言和它的名字,请不要尝试在 scala 中这样做

标签: scala for-loop decrement


【解决方案1】:

也许你需要括号:

var max = ("9" * digit).toInt
var min = ("1"+"0"*(digit-1)).toInt

【讨论】:

  • 我想通了..感谢您的帮助!
  • @O.Chounry 如果某个答案适合您,您可以接受它。
【解决方案2】:

另一种选择是首先避免使用字符串 - 看起来使用 Math.pow 更直接地表示您想要实现的目标:

val max = Math.pow(10, digit) - 1 // e.g. 9999.0 for digit = 4
val min = Math.pow(10, digit - 1) // e.g. 1000.0 for digit = 4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-06
    • 2011-05-16
    • 2011-12-22
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2016-10-13
    相关资源
    最近更新 更多