Question

I want to check if my string contains only allowed character. Matcher works properly, but when I input something like this "123A" app crashes. For only letters it work properly(error). How can I do that?

My code:

pattern = Pattern.compile("[0-9]");
matcher = pattern.matcher(stNumber);
  if(matcher.find())
else
   error

This is my logcat error:

03-07 21:49:50.917    1891-1891/com.converter_numeralsystem.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.converter_numeralsystem.app, PID: 1891
java.lang.NumberFormatException: Invalid long: "112a"
        at java.lang.Long.invalidLong(Long.java:124)
        at java.lang.Long.parse(Long.java:361)
        at java.lang.Long.parseLong(Long.java:352)
        at java.lang.Long.parseLong(Long.java:318)
        at com.converter_numeralsystem.app.MainActivity.calculate(MainActivity.java:121)
        at com.converter_numeralsystem.app.MainActivity.onClick(MainActivity.java:246)
        at android.view.View.performClick(View.java:4438)
        at android.view.View$PerformClick.run(View.java:18422)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)
Était-ce utile?

La solution

If you want to allow only numbers, you should use a regular expression to match the whole string (add + to check for at least one digit). Also, use matches() method instead of find() to match the whole input string (your problem is that find() finds the first match and then doesn't try to match the rest):

pattern = Pattern.compile("[0-9]+");
matcher = pattern.matcher(stNumber);
  if(matcher.matches())
else
   error

Autres conseils

Try

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

Or

pattern = Pattern.compile("\\d+");

Also use

if(matcher.match())

Instead of

if(matcher.find())

If you have an edit text for which you want to introduce only numbers you could add this attribute to your edit text in your xml file:

android:digits="0123456789"
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top