2016年7月28日 星期四

Java內判斷String是否為有效數字的方式

通常要把String轉換為Integer時,都得先知道String的內容是不是純數字,這樣轉換才會正確;所以找了一下判斷的方式,有NumberUtils.isNumber()、StringUtils.usNumeric()和StringUtils.isNumericSpace()三種,要使用這些方法的話,必需要下載Apache Commons Lang的封包檔,並匯入到Project內。

Apache Commons Lang可去其官網處下載:
http://commons.apache.org/proper/commons-lang/download_lang.cgi

像我便是下載commons-lang3-X.X-bin.zip,解壓縮後把其中的jar檔匯入到Eclipse的Project內。

接著撰寫程式:
  1. import java.util.*;
  2. import org.apache.commons.lang3.math.NumerUtils;
  3.  
  4. public class XXX {
  5.  
  6.     public static void main(String[] args)
  7.     {
  8.         String testString = "A1";
  9.  
  10.         System.out.rintln( NumberUtils.isNumber( testString ) );
  11.     }
  12. }
是文字便為false,是數字便為true。

沒有留言:

張貼留言