Java如何判断输入的是字符还是数字?

 我来答
勤奋的小芊芊儿
推荐于2019-08-20 · TA获得超过1.2万个赞
知道小有建树答主
回答量:101
采纳率:100%
帮助的人:9.4万
展开全部
  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;

  2. 用正则表达式:

    首先要import java.util.regex.Pattern 和 java.util.regex.Matcher

    public boolean isNumeric(String str)

    Pattern pattern = Pattern.compile("[0-9]*");

    Matcher isNum = pattern.matcher(str);

    if( !isNum.matches() )

    return false;

  3. 使用org.apache.commons.lang:

    org.apache.commons.lang.StringUtils;

    boolean isNunicodeDigits=StringUtils.isNumeric("aaa123456789");

    http://jakarta.apache.org/commons/lang/api-release/index.html下面的解释:

    isNumeric

    public static boolean isNumeric(String str)Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false.

    null will return false. An empty String ("") will return true.

    StringUtils.isNumeric(null)   = false

    StringUtils.isNumeric("")     = true

    StringUtils.isNumeric("  ")   = false

    StringUtils.isNumeric("123")  = true

    StringUtils.isNumeric("12 3") = false

    StringUtils.isNumeric("ab2c") = false

    StringUtils.isNumeric("12-3") = false

    StringUtils.isNumeric("12.3") = false

    Parameters:

    str - the String to check, may be null

    Returns:

    true if only contains digits, and is non-null

推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式