我正在编写一个计算校验和的程序,但需要删除前面的所有前导零。我知道如何删除一个,但我将如何删除它们?
这是我到目前为止所拥有的:
Scanner scan = new Scanner(System.in);
System.out.print("Enter the first 9 digits of an ISBN as an integer: ");
ISBN = scan.nextInt();
/******************************************************************************
* Processing Section *
******************************************************************************/
processingISBN = ISBN;
sum = 0;
for (int i = 2; i <= 10; i++)
{
digit = processingISBN % 10; // digit at the end
sum = sum + i * digit;
processingISBN = processingISBN / 10;
}
firstDigit = ISBN / 100000000; // grab first digit (in case of zero)
/******************************************************************************
* Outputs Section *
******************************************************************************/
// print out check sum number, use X for 10
if (firstDigit == 0)
{
System.out.print("The ISBN-10 number is 0" + ISBN);
}
if (firstDigit != 0)
{
System.out.print("The ISBN-10 number is " + ISBN);
}
if(sum % 11 == 1) //checks for checksum=10
{
System.out.print("X");
}
else if (sum % 11 == 0)
{
System.out.print("0");
}
else
{
System.out.print(11 - (sum % 11));
}
我应该注意:ISBN必须作为整数处理,而不是字符串。
答案 0 :(得分:0)
试试这个,将ISBN构建为字符串,然后运行:
String yourInputAsString = "0000002514";
int yourInputAsInt;
Pattern p = Pattern.compile("^\\d+$");
Matcher m = p.matcher(yourInputAsString);
if(m.matches()){
yourInputAsInt = Integer.valueOf(yourInputAsString.replaceAll("^0+", ""));
System.out.println("As String: " + yourInputAsString.replaceAll("^0+", ""));
System.out.println("As Int: " + yourInputAsInt);
//do check
} else {
System.out.println(yourInputAsString);
}
<强>输出:强>
字符串:2514
作为Int:2514