Java Luhn算法卡号生成器
时间: 2023-07-10 16:23:30 浏览: 322
Luhn算法是一种用于验证卡号、信用卡号等一些标识号码有效性的算法。以下是一个基于Java语言实现的Luhn算法卡号生成器:
```java
import java.util.Random;
public class LuhnCardGenerator {
private static final int CARD_NUMBER_LENGTH = 16;
public static void main(String[] args) {
String cardNumber = generateCardNumber();
System.out.println("Generated card number: " + cardNumber);
}
private static String generateCardNumber() {
Random random = new Random();
StringBuilder sb = new StringBuilder();
// Generate first 15 digits randomly
for (int i = 0; i < CARD_NUMBER_LENGTH - 1; i++) {
sb.append(random.nextInt(10));
}
// Calculate the Luhn check digit
int checkDigit = calculateCheckDigit(sb.toString());
sb.append(checkDigit);
return sb.toString();
}
private static int calculateCheckDigit(String cardNumber) {
int sum = 0;
boolean isSecondDigit = false;
for (int i = cardNumber.length() - 1; i >= 0; i--) {
int digit = Integer.parseInt(cardNumber.substring(i, i + 1));
if (isSecondDigit) {
digit *= 2;
if (digit > 9) {
digit = digit % 10 + 1;
}
}
sum += digit;
isSecondDigit = !isSecondDigit;
}
return (10 - sum % 10) % 10;
}
}
```
该算法生成一个16位的随机卡号,并且最后一位是Luhn算法的校验位。可以通过调用`generateCardNumber()`方法来获得生成的卡号。
阅读全文