首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >处理多个前导零

处理多个前导零
EN

Stack Overflow用户
提问于 2015-10-07 04:15:16
回答 1查看 66关注 0票数 0

我正在写一个计算校验和的程序,但需要删除前面的所有前导零。我知道如何只删除一个,但我如何删除它们全部?

这是我到目前为止所知道的:

代码语言:javascript
复制
 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必须作为整数处理,而不是字符串。

EN

回答 1

Stack Overflow用户

发布于 2015-10-07 04:41:23

尝试这样做,将ISBN构建为字符串,然后运行以下命令:

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32978896

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档