2010-09-02 94 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