Scala:检查字符串是否只有表现奇怪的数字

Scala: checking String for only digits behaving strange

我写了代码,当我申请入学时,它按预期工作不为空只有数字或不仅有数字的字符串:

   def checkDigits(nameOrId: String): Unit = {

      def isAllDigits(x: String) = x forall (c => c.isDigit)

      if (isAllDigits(nameOrId)) print("WITH_ID ")
      else print("WITH_NAME")
  }

但是当我申请入口“”-值时,它打印的不是“WITH_NAME”,而是“WITH_ID”。所以它将“”识别为数字字符!

我哪里做错了,我该如何改进我的代码?

forall 方法检查集合中所有值的测试是否为真。如果没有值它 returns true,因为所有值都通过了测试。

对于您想要的行为,您需要添加额外的测试:

def isAllDigits(x: String) = x.nonEmpty && x.forall(_.isDigit)

正则表达式替代方法正在使用 matches,它应该匹配整个字符串并匹配 1 个或多个数字。

请注意您的方法 def checkDigits returns Unit 因为您只是在打印。要使其 return 成为布尔值,您可以使用:

def checkDigits(x: String) = x.matches("\d+")