android check if string contains characters other than 0-9

ⅰ亾dé卋堺 提交于 2019-12-13 04:46:06

问题


I am creating an app for counting points in games. This app has a edittext component. I want to check if the string retrieved from the edit text contains characters other than 0-9. This is because my app contains a integer.parse function wich crashes if characters other than 0-9 is inputed. All help will be greatly appreciated. Thanks in advance.


回答1:


If you just want to notify the user of an invalid character then you can wrap it in a try/catch and act accordingly

try
{
    int someInt = Integer.parseInt(et.getText().toString());
    // other code
}
catch (NumberFormatException e)
{
    // notify user with Toast, alert, etc...
}

You also can use a regular expression to look for the characters you want/don't want depending on your needs.

Just to be clear in case my code comment wasn't, I am suggesting that you do something with the exception and notify the user. Don't catch it and let it sit




回答2:


public static boolean isNumeric(String str)
{
    for (char c : str.toCharArray())
    {
        if (!Character.isDigit(c)) return false;
    }
    return true;
}

OR

public boolean isNumeric(String s) {  
    return s.matches("[-+]?\\d*\\.?\\d+");  
} 



回答3:


Firstly you can setup edittext as integer numbers only, so in your layout put

android:inputType="number"

It will set to integer numbers only in edit text.

All possible types here: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType

Then you can test with regular expression or/and catch exception when parsing. Regular expression would be:

"string".matches("\\d+") // true when numbers only, false otherwise

Reference here:

http://developer.android.com/reference/java/lang/String.html#matches(java.lang.String) http://developer.android.com/reference/java/util/regex/Pattern.html



来源:https://stackoverflow.com/questions/19988434/android-check-if-string-contains-characters-other-than-0-9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!