2010-09-02 93 views
0

此代码验证ISBN是否有效。对于九位输入,我想通过计算并附加校验码来形成有效的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); 
    } 
+0

是这功课吗? – dtb 2010-09-02 20:05:37

+0

不是它是一本书的练习 – 2010-09-02 20:31:39

回答

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); 
} 
+0

感谢您的帮助,我很欣赏它,但程序必须能够同时做到这一点。因为最后一部分是在控制台之上添加一个表单,并使其具有两个按钮,一个用于验证和一个生成。 – 2010-09-02 20:34:44

+0

@Michael。这就是为什么上面是一个带有新名称的单独方法,您可以添加到相关类中。可以重构来消除重复,但首先要弄清楚为什么你们两个先工作。 – 2010-09-02 20:52:53