java中判断字符串是否为数字的两种方法

    技术2022-05-11  62

    1用JAVA自带的函数 public   static   boolean  isNumeric(String str){   for  ( int  i  =   0 ; i  <  str.length(); i ++ ){   System.out.println(str.charAt(i));    if  ( ! Character.isDigit(str.charAt(i))){     return   false ;   }  }   return   true ; } 2用正则表达式 public   boolean  isNumeric(String str){    Pattern pattern  =  Pattern.compile( " [0-9]* " );    Matcher isNum  =  pattern.matcher(str);    if ! isNum.matches() ){        return   false ;    }     return   true ; } 

     例子:

    import  java.util.regex.Matcher; import  java.util.regex.Pattern; public   class  tel {     public boolean isNumeric(String str){    Pattern pattern = Pattern.compile("[0-9]*");    Matcher isNum = pattern.matcher(str);   if!isNum.matches() ){       return false;    }    return true; }         private String toNo(String telno){        String temp="";        int j=0;                if(isNumeric(telno))        {            return telno;        }        else{            for(int i=0;i<telno.length();i++){                if(!(Character.isDigit(telno.charAt(i)))){                    continue;                }                else                {                    temp += telno.charAt(i);                }            }        }        return temp;    }        public static void main(String[] args){    tel test = new tel();    String no="0592-3924063";    String no2="(0592)3924063";    String no3="05923924063";    System.out.println(test.toNo(no));     System.out.println(test.toNo(no2));     System.out.println(test.toNo(no3)); }}

    最新回复(0)