Isbn生成校验位

时间:2010-09-02 19:54:27

标签: c# c#-3.0

此代码验证ISBN是否有效。对于九位数输入,我想通过计算和附加校验位来形成有效的ISBN。对于少于九位的输入,我希望它返回错误消息“请输入正确的数字”。我应该怎么做呢?

   public class isbn
    {   //attributes
         private string isbnNum;
         //method   
         public string GetIsbn()
         {
             return this.isbnNum;
         }
           //constructor
           public isbn()
           {
               Console.Write("Enter Your ISBN Number: ");
               this.isbnNum = Console.ReadLine();

           }//end default constructor

            //method
           public string displayISBN()
           {

               return  this.GetIsbn();

           }


       public static void Main(string[] args)
        {
            //create a new instance of the ISBN/book class

            isbn myFavoriteBook = new isbn();

            //contains the method for checking validity 
            bool isValid = CheckDigit.CheckIsbn(myFavoriteBook.GetIsbn());

            //print out the results of the validity.
            Console.WriteLine(string.Format("Your book {0} a valid ISBN",
                                       isValid ? "has" : "doesn't have"));

            Console.ReadLine();

        }

public static class CheckDigit
{       // attributes
    public static string NormalizeIsbn(string isbn)
    {
        return isbn.Replace("-", "").Replace(" ", "");
    }
   public static bool CheckIsbn(string isbn) // formula to check ISBN's validity
    {
        if (isbn == null)
            return false;

        isbn = NormalizeIsbn (isbn);
        if (isbn.Length != 10)
            return false;

        int result;
        for (int i = 0; i < 9; i++)
            if (!int.TryParse(isbn[i].ToString(), out result))
                return false;

        int sum = 0;
        for (int i = 0; i < 9; i++)
            sum += (i + 1) * int.Parse(isbn[i].ToString());

        int remainder = sum % 11;
        if (remainder == 10)
            return isbn[9] == 'X';
        else
            return isbn[9] == (char)('0' + remainder);
    }

1 个答案:

答案 0 :(得分:3)

只需更改它以附加最后一个字符,而不是检查它是否存在。以上内容可以清理一下,但只需根据需要进行更改即可:

public static string MakeIsbn(string isbn) // string must have 9 digits
{
    if (isbn == null)
        throw new ArgumentNullException();

    isbn = NormalizeIsbn (isbn);
    if (isbn.Length != 9)
        throw new ArgumentException();

    int result;
    for (int i = 0; i != 9; i++)
        if (!int.TryParse(isbn[i].ToString(), out result))
            throw new ArgumentException()

    int sum = 0;
    for (int i = 0; i != 9; i++)
        sum += (i + 1) * int.Parse(isbn[i].ToString());

    int remainder = sum % 11;
    if (remainder == 10)
        return isbn + 'X';
    else
        return isbn + (char)('0' + remainder);
}