Isbn生成校验位 [英] Isbn generate the check digit
本文介绍了Isbn生成校验位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码验证ISBN是否有效。对于九位数的输入,我想通过计算并附加校验位来形成有效的ISBN。对于少于9位数字的输入,我希望它返回错误消息请输入正确的数字。我应该如何处理?
This code verifies whether an ISBN is valid. For nine-digit inputs, I'd like to form a valid ISBN by calculating and appending the check digit. For inputs less than nine digits, I'd like it to return the error message "Please enter a correct number". How should I go about this?
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);
}
推荐答案
只需将其更改以追加最后一个字符,而不是检查它是否存在。上面的内容可能会被清除,但是只是根据需要进行更改会导致:
Just change it to append the last character rather than checking that it's present. The above could be cleaned up a bit, but just changing it as required results in:
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);
}
这篇关于Isbn生成校验位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文