检查输入的值是否为数字

17

我尝试了这段代码片段,但它没有起作用。

try 
    {
    Integer.parseInt(enteredID.getText().toString());
    Log.i("enteredID value", "enterdID is numeric!!!!!!!!!!!^^^");
    flag=1;
} catch (NumberFormatException e) {
    flag=-1;
    Log.i("enteredID value", "enterdID isn't numeric!!!!!!!!!!!^^^");
}

请注意,它必须能够接受用户名或ID来检查值,我不希望它只接受数字!

13个回答

23
如果布尔值为true,则它是数字,否则为字符串值。
boolean digitsOnly = TextUtils.isDigitsOnly(editText.getText());

或者举个例子。
String text = edt_email.getText().toString();
            boolean digitsOnly = TextUtils.isDigitsOnly(text);
            if (digitsOnly) {
                 if (text.length() == 0) {
                    Toast.makeText(getApplicationContext(), "field can't be empty.", Toast.LENGTH_LONG).show();
                 } else {
                   Toast.makeText(getApplicationContext(), "field is int value", Toast.LENGTH_LONG).show();
                 }
            }else {
                    Toast.makeText(getApplicationContext(), "Field is string value", Toast.LENGTH_LONG).show();
                }
            }

21

使用这个表达式只验证数字

String regexStr = "^[0-9]*$";

if(et_number.getText().toString().trim().matches(regexStr))
{
    //write code here for success
}
else{
    // write code for failure
}

这对我有用,但我想允许小数,当我复制像33.8这样的数字时,它失败了...我该如何更新regexStr以允许小数点? - Wayne Johnson
你需要将这个字符串 "^[0-9]$" 替换为 "^[1-9]\d(.\d+)?$"。 - Dhaval Patel
1
为我工作。但在Android中使用"^[1-9]\\d*(\\.\\d+)?$"。谢谢。 - Hoang Duc Tuan

7

将EditText属性inputType设置为number,它将始终将数字作为输入

android:inputType="number"

谢谢,但我写了一条注释,希望用户输入数字和字符,以便执行每个不同的代码片段。 - A.J

5

尝试使用这个正则表达式:

String regex = "-?\\d+(\\.\\d+)?";

if (enteredID.getText().toString().matches(regex))  {
     Log.i("enteredID value", "enterdID is numeric!!!!!!!!!!!^^^");
     flag=1;
 } else {
     flag=-1;
     Log.i("enteredID value", "enterdID isn't numeric!!!!!!!!!!!^^^");
 }

5
使用 TextUtils 类的函数来实现。
TextUtils.isDigitsOnly("gifg");

如果字符串中只有数字,它将返回true,如果存在任何字符,则返回false。


2
请使用这个方法。
 boolean isNumber(String string) {
    try {
      int amount = Integer.parseInt(string);
      return true;
    } catch (Exception e) {
      return false;
    }
  }

像这样:

if (isNumber(input)) {
  // string is int
}

0
String text = editText123.getText().toString();
try {
   int num = Integer.parseInt(text);
   Log.i("",num+" is a number");
} catch (NumberFormatException e) {
   Log.i("",text+" is not a number");
}

0
Pattern ptrn = Pattern.compile(regexStr);

if (!ptrn.matcher(et_number.getText().toString().trim()).matches()) {

    //write code here for success

}else{

    //write code here for success

}

0

0

也许是这样的:

    String text = enteredID.getText().toString();

    if(text.matches("\\w+")){
      //--words--
    }else if (text.matches("\\d+")){
      //--numeric--
    }else {
      //-- something else --
    }

您可以更改正则表达式以匹配复杂格式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接