1

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;
}
Son Goku
  • 21
  • 5
  • so doesn't this work ? – Madhawa Priyashantha Jul 29 '15 at 13:32
  • So you are able to put down a complicated test that checks for "Luhn CRC"; but you are unable to first check the same string if it contains non-digits? Hint: try doing prior research, for example searching for certain keywords; pointing out http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-a-numeric-type-in-java easily? – GhostCat Jul 29 '15 at 13:39
  • This is just code that is freely available on the internet, I did not create it myself. – Son Goku Jul 29 '15 at 14:07
  • You should get better sources for copying, then. This is not a high quality piece of code. That thing with the string buffer and the reverse is not really needed. Better yet, put in the effort to learn to program yourself. It will pay in the long run. – RealSkeptic Jul 29 '15 at 18:55

2 Answers2

2

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.

Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58
  • Could you elaborate more on the Integer.parseInt(...) because that's what I thought and I tried it but I must have either passed a wrong argument or put it in the wrong place (hence my need to ask this question). If you could tell me where it fits in the code I would greatly appreciate it. – Son Goku Jul 29 '15 at 21:56
  • `public boolean isDigit(String something) { try { return Long.parseLong( something) >= 0; } catch(NumberFormatException e) { return false; } }` – Florian Schaetz Jul 30 '15 at 04:29
0

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
mattinbits
  • 10,370
  • 1
  • 26
  • 35