using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Books { public partial class Book { /// /// Validiert die ISBN und wirft eine ArgumentException, /// falls sie ungültig ist. /// /// /// true, wenn gültig /// public static bool CheckIsbn(string isbn) { if (!IsValidLength(isbn)) { throw new ArgumentException($"ISBN {isbn} has no length of 10!"); } if (!IsValidChar(isbn)) { throw new ArgumentException("Invalid character spotted: valid characters must be between 0 and 9"); } int checkSumValue = GetCheckSum(isbn) % 11; if (checkSumValue != 0) { throw new ArgumentException("Invalid checksum"); } return true; } private static bool IsValidLength(string isbn) { return isbn.Length == 10; } private static bool IsValidChar(string isbn) { if (isbn[isbn.Length - 1] == 'X' || isbn[isbn.Length - 1] == 'x') { for (int i = 0; i < isbn.Length - 1; i++) { if (isbn[i] < '0' || isbn[i] > '9') { return false; } } return true; } else { for (int i = 0; i < isbn.Length; i++) { if (isbn[i] < '0' || isbn[i] > '9') { return false; } } } return true; } private static bool LastCharIsX(string isbn) { return isbn[isbn.Length - 1] == 'x' || isbn[isbn.Length - 1] == 'X'; } public static int GetCheckSum(string isbn) { int[] numbers = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; int sum = 0; for (int i = 0; i < isbn.Length - 1; i++) { sum += (isbn[i] - '0') * numbers[i]; } if (LastCharIsX(isbn)) { sum += 10 * numbers[numbers.Length - 1]; } else { sum += (isbn[isbn.Length - 1] - '0') * numbers[numbers.Length - 1]; } return sum; } /// /// Eine gültige ISBN-Nummer besteht aus den Ziffern 0, ... , 9, /// 'x' oder 'X' (nur an der letzten Stelle) /// Die Gesamtlänge der ISBN beträgt 10 Zeichen. /// Für die Ermittlung der Prüfsumme werden die Ziffern /// von rechts nach links mit 1 - 10 multipliziert und die /// Produkte aufsummiert. Ist das rechte Zeichen ein x oder X /// wird als Zahlenwert 10 verwendet. /// Die Prüfsumme muss modulo 11 0 ergeben. /// /// Prüfergebnis public static bool CheckIsbn(string isbn, out string errorMsg) { errorMsg = "Your ISBN is valid"; if (!IsValidLength(isbn)) { errorMsg = $"ISBN {isbn} has no length of 10!"; return false; } if (!IsValidChar(isbn)) { errorMsg = "Invalid character spotted: valid characters must be between 0 and 9"; return false; } int checkSumValue = GetCheckSum(isbn) % 11; if (checkSumValue != 0) { errorMsg = "Invalid checksum"; return false; } return true; } } }