Ocena użytkownikóww: ***** / 3
Nadesłany przez Tomasz Lubiński, 02 kwietnia 2007 01:00
Kod przedstawiony poniżej przedstawia główną część rozwiązania problemu.
Pobierz pełne rozwiązanie.Jeżeli nie odpowiada Ci sposób formatowania kodu przez autora skorzystaj z pretty printer'a i dostosuj go automatycznie do siebie.
Luhn.java:
//algorytm Luhn'a
//www.algorytm.org
//(c)2007 by Tomasz Lubinski
public class Luhn {
private static final byte DoubleArray[] = {0, 2, 4, 6, 8, 1, 3, 5, 7, 9};
/**
* Check number
* @param number
* @return check digit
*/
public static int luhnCheckDigit(String number) {
int sum = 0;
for (int i=2; i<=number.length(); i++) {
if (i%2 != 0) {
sum += Integer.parseInt(number.charAt(number.length() - i) + "");
} else {
sum += DoubleArray[Integer.parseInt(number.charAt(number.length() - i) + "")];
}
}
sum %= 10;
sum = 10 - sum;
sum %= 10;
return sum;
}
/**
* Check number - Luhn algorithm
* @param number
* @return true if check digit in number is correct, false otherwise
*/
public static boolean luhnCheck(String number) {
int sum = 0;
for (int i=1; i<=number.length(); i++) {
if (i%2 != 0) {
sum += Integer.parseInt(number.charAt(number.length() - i) + "");
} else {
sum += DoubleArray[Integer.parseInt(number.charAt(number.length() - i) + "")];
}
}
if (sum % 10 == 0) {
return true;
}
return false;
}
/**
* Get number and check it
*
* @param args
*/
public static void main(String[] args) {
String number;
System.out.println("Podaj numer do sprawdzenia");
number = Console.readString();
if (luhnCheck(number)) {
System.out.println("Numer jest prawidłowy");
} else {
System.out.println("Numer jest nieprawidłowy");
}
}
}