如何在scala中检查用户输入类型(数据类型)?

问题描述 投票:0回答:2

我想在scala中从控制台检查用户输入类型(数据类型)?我需要检查输入数据是Int,String,Double,Float。

scala bigdata
2个回答
0
投票

在这种情况下你可以使用scala最强的api match case作为

scala>     def findDataType(x: Any) = x match {
     |       case x : String => println("String identified")
     |       case x : Int => println("Integer identified")
     |       case x : Float => println("Float identified")
     |       case x : Double => println("Double identified")
     |       case _ => println("DataType not identified")
     |     }
findDataType: (x: Any)Unit

scala> findDataType("abcd")
String identified

scala> findDataType(1)
Integer identified

scala> findDataType(1.0)
Double identified

scala> findDataType(1D)
Double identified

scala> findDataType(1f)
Float identified

scala> findDataType('c')
DataType not identified

我们可以从控制台读入并传递给上面的函数

scala> findDataType(scala.io.StdIn.readInt())
Integer identified

scala> findDataType(scala.io.StdIn.readLine())
String identified

scala> findDataType(scala.io.StdIn.readFloat())
Float identified

编辑

您可以使用如下的正则表达式模式(我只使用整数和浮点数)

scala> val INT_PATTERN: String = "^[-+]?[0-9]*$"
INT_PATTERN: String = ^[-+]?[0-9]*$

scala>   val FLOAT_PATTERN: String = "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$"
FLOAT_PATTERN: String = ^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$

并将函数定义为

scala> def findDataType(value: Any) = {
     | if(value.toString.matches(INT_PATTERN)) println("Integer identified")
     | else if(value.toString.matches(FLOAT_PATTERN)) println("Float identified")
     | else println("String identified")
     | }
findDataType: (value: Any)Unit

使用scala.io.StdIn.readLine()调用函数如下所示将给出确切的数据类型

scala> findDataType(scala.io.StdIn.readLine()) // 2 is entered
Integer identified

scala> findDataType(scala.io.StdIn.readLine()) //ab is entered
String identified

scala> findDataType(scala.io.StdIn.readLine()) // 2.1 is entered
Float identified

这也可以用于其他数据类型。


0
投票

我会直接使用输入,而不是检查类型。尝试:

val input = scala.io.StdIn.readLine() 

if (Try(input.toInt).isSuccess) ...  // It is an integer
else if (Try(input.toFloat).isSuccess) ... // It is a float
else if (Try(input.toDouble).isSuccess) ... // It is a double
else ... // No need to convert to string
© www.soinside.com 2019 - 2024. All rights reserved.