Son Goku
Son Goku

Reputation: 21

Test a string for non-numerical characters Luhn Test Java

How do I test the input String for non numerical characters and then return false if there are non-numerical characters found.

private static boolean luhnTest(String number){
    int s1 = 0, s2 = 0;
    String reverse = new StringBuffer(number).reverse().toString();

    for(int i = 0 ;i < reverse.length();i++)
    {
        int digit = Character.digit(reverse.charAt(i), 10);
        if(i % 2 == 0){//this is for odd digits, they are 1-indexed in the algorithm
            s1 += digit;
        }
        else
        {//add 2 * digit for 0-4, add 2 * digit - 9 for 5-9
            s2 += 2 * digit;
            if(digit >= 5)
            {
                s2 -= 9;
            }
        }
    }
    return (s1 + s2) % 10 == 0;
}

Upvotes: 1

Views: 143

Answers (2)

mattinbits
mattinbits

Reputation: 10428

Remove all the digits, and see if anything is left:

public class DigitsCheck{

         public static boolean isOnlyDigits(String input) {
             return (input.replaceAll("\\d", "").length() == 0);
         }

         public static void main(String []args){
            System.out.println(isOnlyDigits("abc123"));
            System.out.println(isOnlyDigits("123"));
         }
    }

Produces

false
true

Upvotes: 0

Florian Schaetz
Florian Schaetz

Reputation: 10662

One way would be a regular expression ("\d*"), see the Pattern class. Another one, but a little bit smelly, would simply be to use Integer.parseInt (...) (or Long.parseLong( ...) ) and catch the Exception.

Upvotes: 2

Related Questions