Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Ejecutable {
- public static void main(String[] args) {
- testMethod("0-7475-3269-9", "3-04-013311-X", "304013311X",
- "0747532699", "A0-7475-3269-9", "045747535679", "0000000000");
- }
- public static boolean isISBNCode(final String pCode) {
- boolean result = false;
- if (pCode != null && !pCode.isEmpty()) {
- // Verifico el formato en que viene y lo estandarizo:
- // Si viene con "-" los elimino, si viene con letras no es válido.
- String codeFormat = pCode;
- if (pCode.contains("-")) {
- codeFormat = pCode.replace('-', ' ');
- codeFormat = codeFormat.replaceAll("\\s+", "");
- }
- if (codeFormat.length() == 10
- && tryParseInt(codeFormat.substring(0,
- codeFormat.length() - 2))) {
- String lastDigit = String.valueOf(codeFormat.charAt(codeFormat
- .length() - 1));
- if (tryParseInt(lastDigit)
- || "X".equals(lastDigit.toUpperCase())) {
- char[] codeArray = codeFormat.toCharArray();
- int position = 10;
- int totalSum = 0;
- for (char character : codeArray) {
- if (position != 1) {
- totalSum = totalSum
- + (Integer.parseInt(character + "") * position);
- position--;
- } else {
- // Último dígito, hay que verificar.
- if ("X".equals(character + "".toUpperCase())) {
- totalSum = totalSum
- + (Integer.parseInt("10") * position);
- } else {
- totalSum = totalSum
- + (Integer.parseInt(character + "") * position);
- }
- }
- }
- // Verifico si el totalSum es múltiplo de 11.
- if (totalSum % 11 == 0) {
- result = true;
- }
- }
- }
- }
- return result;
- }
- public static boolean tryParseInt(final String pString) {
- boolean result = false;
- try {
- Integer.parseInt(pString);
- result = true;
- } catch (NumberFormatException exception) {
- result = false;
- }
- return result;
- }
- public static void testMethod(final String... pValues) {
- if (pValues.length > 0) {
- for (String value : pValues) {
- if (isISBNCode(value)) {
- System.out.println("El código " + value + " es válido.");
- } else {
- System.out.println("El código " + value + " NO es válido.");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement