我正在写一个计算校验和的程序,但需要删除前面的所有前导零。我知道如何只删除一个,但我如何删除它们全部?
这是我到目前为止所知道的:
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必须作为整数处理,而不是字符串。
发布于 2015-10-07 04:41:23
尝试这样做,将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);
}输出:
As字符串: 2514
As接口: 2514
https://stackoverflow.com/questions/32978896
复制相似问题