Untitled
unknown
java
a year ago
1.9 kB
12
Indexable
public class RegonValidator {
public static boolean validateRegon(String regon) {
if (regon == null || !(regon.length() == 9 || regon.length() == 14)) {
return false; // REGON powinien mieć 9 lub 14 cyfr
}
try {
int[] weights9 = {8, 9, 2, 3, 4, 5, 6, 7}; // Wagi dla 9-cyfrowego REGONu
int[] weights14 = {2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 0, 0, 0}; // Wagi dla 14-cyfrowego REGONu
// Długość 9 cyfr
if (regon.length() == 9) {
return validateChecksum(regon, weights9);
}
// Długość 14 cyfr
if (regon.length() == 14) {
if (!validateChecksum(regon.substring(0, 9), weights9)) {
return false; // Najpierw sprawdzamy pierwsze 9 cyfr
}
return validateChecksum(regon, weights14); // Potem pełne 14 cyfr
}
} catch (NumberFormatException e) {
return false; // Jeśli nie jest liczbą
}
return false;
}
private static boolean validateChecksum(String regon, int[] weights) {
int sum = 0;
for (int i = 0; i < weights.length; i++) {
sum += Character.getNumericValue(regon.charAt(i)) * weights[i];
}
int controlDigit = sum % 11;
if (controlDigit == 10) {
controlDigit = 0;
}
return controlDigit == Character.getNumericValue(regon.charAt(weights.length));
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Podaj numer REGON do walidacji:");
String regon = scanner.nextLine();
if (validateRegon(regon)) {
System.out.println("Numer REGON jest poprawny.");
} else {
System.out.println("Numer REGON jest niepoprawny.");
}
scanner.close();
}
}Editor is loading...
Leave a Comment