写一个随机生成IMEI的java代码
时间: 2023-08-21 18:07:37 浏览: 46
以下是一个简单的生成随机IMEI的Java代码:
```java
import java.util.Random;
public class IMEIGenerator {
private static final int[] WEIGHTS = { 2, 1, 2, 6, 5, 4, 3, 2 };
public static void main(String[] args) {
String imei = generateIMEI();
System.out.println("Randomly generated IMEI: " + imei);
}
public static String generateIMEI() {
Random rand = new Random();
// Generate the first 14 digits randomly
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 14; i++) {
sb.append(rand.nextInt(10));
}
// Calculate the check digit using the Luhn algorithm
int sum = 0;
for (int i = 0; i < 14; i++) {
int digit = Integer.parseInt(sb.substring(i, i + 1));
sum += digit * WEIGHTS[i % 8];
}
int checkDigit = (10 - (sum % 10)) % 10;
// Append the check digit to the end of the IMEI
sb.append(checkDigit);
return sb.toString();
}
}
```
这个程序首先生成前14位数字,然后使用Luhn算法计算最后一位的校验数字。最后将校验数字附加到IMEI末尾并返回。