How can I get each digit of a 16 digit number and store each digit as a variable? [closed]

StackOverflow https://stackoverflow.com/questions/19552210

  •  01-07-2022
  •  | 
  •  

سؤال

I need to write a Java program that validates credit card numbers, and to do that I need to preform operations on each individual digit. How can I get these digits, without using strings or arrays?

هل كانت مفيدة؟

المحلول

int number; (This would be your credit card number)

while (number > 0) {
    System.out.println( number % 10);
    number = number / 10;
}

This will print them in reverse order. You can perform your operations on the digits this way.

نصائح أخرى

Assuming you're using a 64 bit integral type (which is sufficient for a 16 digit card number), a long will do the trick; e.g. long num.

use num % 10 to extract the rightmost digit.

use num / 10 to remove the rightmost digit.

That's all you need to do (in a loop structure obviously), but why do it like this anyway? Do a good job instead. Use http://en.wikipedia.org/wiki/Luhn_algorithm with which credit card numbers comply.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top