import java.util.Scanner;
public class ISBNChecker {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a 10-digit ISBN number: ");
String isbn = input.next();
if (isValidISBN(isbn)) {
System.out.println(isbn + " is a valid ISBN number.");
} else {
System.out.println(isbn + " is not a valid ISBN number.");
}
}
public static boolean isValidISBN(String isbn) {
if (isbn.length() != 10) {
return false;
}
int sum = 0;
for (int i = 0; i < 9; i++) {
char c = isbn.charAt(i);
if (!Character.isDigit(c)) {
return false;
}
sum += (c - '0') * (i + 1);
}
char last = isbn.charAt(9);
if (last == 'X') {
sum += 10;
} else if (Character.isDigit(last)) {
sum += (last - '0') * 10;
} else {
return false;
}
return (sum % 11 == 0);
}
}
Enter a 10-digit ISBN number: 1259060977
1259060977 is a valid ISBN number.
Enter a 10-digit ISBN number: 5236027917
5236027917 is not a valid ISBN number.
isValidISBN()
method to check if the entered string is a valid ISBN number.isValidISBN()
method checks if the length of the string is 10. If it is not, then it returns false. Then, it calculates the sum
of the first 9 digits of the ISBN number, multiplied by their position, and adds the last digit (which could be a digit or an 'X') multiplied by 10
. sum
is divisible by 11
, then the ISBN number is valid, and the method returns true. Otherwise, it returns false.