2015-10-06 31 views
0

我在寫一個計算校驗和的程序,但需要刪除前面的所有前導零。我知道如何去除一個,但我將如何去除它們?處理多個前導零

這是我到目前爲止有:

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)); 
    } 

我應該提到:書號必須作爲一個整數,而不是字符串處理。

+2

如果你正在檢查有人進入'「000012 78126「',你會遇到一些問題:首先,前導零表示八進制(基數爲8),所以你需要捕獲字符串。其次,一個整數不關心前導零,所以00001278126無論如何都只會成爲1278126。 – Makoto

+0

我的Java很臭,但用正則表達式處理您的ISBN,他們搖滾。刪除前導0的ISBN = ISBN.replaceAll(「^ 0」,「」)''。我知道這是不對的,但玩耍。 – jiveturkey

回答

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