在处理数据之前,需要判断能否转为这种类型,一直没找到相应的API,于是自己实现了一个简单粗暴的方法,记录下来,以供交流。
java版本:
package com.mangocool.verify; import java.text.SimpleDateFormat; /** * Created by MANGOCOOL on 2016/9/29. */ public class VerifyTest { public static boolean verify(String str, String type) { try { if("double".equals(type)) { Double.valueOf(str); return true; } else if("int".equals(type)) { Integer.valueOf(str); return true; } else if("date".equals(type)) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.parse(str); return true; } else { return true; } } catch (Exception e) { return false;//如果抛出异常,返回False } } public static void main(String[] args) { String str = "88.8"; System.out.println(verify(str, "double")); System.out.println(verify(str, "int")); System.out.println(verify(str, "date")); } }
scala版本:
package com.mangocool.verify import scala.util.{Success, Try} /** * Created by MANGOCOOL on 2016/9/29. */ object VerifyTest2 { def verify(str: String, dtype: String):Boolean = { var c:Try[Any] = null if("double".equals(dtype)) { c = scala.util.Try(str.toDouble) } else if("int".equals(dtype)) { c = scala.util.Try(str.toInt) } val result = c match { case Success(_) => true; case _ => false; } result } def main (args: Array[String] ): Unit = { val str = "88.8" println(verify(str, "double")) println(verify(str, "int")) println(verify(str, "date")) } }
记录至此,仅供参考,欢迎交流!
分享:
崇尚极简,热爱技术,喜欢唱歌,热衷旅行,爱好电子产品的一介码农。
联系QQ:58742094
联系电话:
工作邮箱:
当你的才华还撑不起你的野心的时候,你就应该静下心来学习,永不止步!
人生之旅历途甚长,所争决不在一年半月,万不可因此着急失望,招精神之萎葸。
Copyright 2015- 芒果酷(mangocool.com) All rights reserved. 湘ICP备14019394号
免责声明:本网站部分文章转载其他媒体,意在为公众提供免费服务。如有信息侵犯了您的权益,可与本网站联系,本网站将尽快予以撤除。