您的位置:首页 > 编程语言 > Java开发

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

2007-03-02 16:55 1031 查看
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));


}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐