2015-07-04 88 views
2

我在介紹Java類,並且在爲信用卡驗證程序編寫校驗和算法時遇到問題。要求是:檢查信用卡號碼的驗證

  • 從右側第二位開始,右至左,雙每隔一個數字;如果結果數大於或等於10,則減去9.將每個結果數加在一起。
  • 然後,從右邊的最後一位數字開始,從右向左,向上一步中使用的運行總數添加其他數字。
  • 如果生成的總數可以被10整除,則信用卡號碼有效。
  • 編碼此算法時,請記住並非所有信用卡號碼都具有相同的位數。

還有人說我們需要使用一個循環來完成這個。我明白,我可能需要一個for循環,但我只是堅持如何完成它。這是我的:

public static boolean isValidNumber(String cardNumber) { 
     //your code here 
     int i, checkSum = 0; 

     // Compute checksum of every other digit starting from right-most digit 
     for (i = cardNumber.Length - 1; i >= 0; i -= 2) { 
      checkSum += (cardNumber[i] - '0'); 
     } 

     // Now take digits not included in first checksum, multiple by two, 
     // and compute checksum of resulting digits 
     for (i = cardNumber.Length - 2; i >= 0; i -= 2) { 
      int val = ((cardNumber[i] - '0') * 2); 
      while (val > 0) { 
       checkSum += (val % 10); 
       val /= 10; 
      } 
     } 

     // Number is valid if sum of both checksums MOD 10 equals 0 
     return ((checkSum % 10) == 0); 
    } 

我在兩個for循環都收到錯誤。 有什麼幫助嗎?

+0

您的循環使用得到的字符串字符(int i = cardNumber.Length - 2; j> = 0; j - = 2) – Andrew

+0

@Andrew謝謝!然而,我仍然得到錯誤,說「數組需要,但字符串發現」我有[我]和[J] ..你知道我可以解決這個問題嗎? – badluckbowers

回答

0
  • 要查找的字符串的長度使用string.length()不string.length減
  • 要在給定的指標使用string.charAt(index)

    public static boolean isValidNumber(String cardNumber) { 
    //your code here 
    int i, checkSum = 0; 
    
    //To find the length of the string use string.length() not string.Length 
    for (i = cardNumber.length() - 1; i >= 0; i -= 2) { 
        //to get char from a string at a given position use string.charAt(index) 
        checkSum += (cardNumber.charAt(i) - '0'); 
    } 
    
    for (i = cardNumber.length() - 2; i >= 0; i -= 2) { 
        int val = ((cardNumber.charAt(i) - '0') * 2); 
        while (val > 0) { 
         checkSum += (val % 10); 
         val /= 10; 
        } 
    } 
    
    // Number is valid if sum of both checksums MOD 10 equals 0 
    return ((checkSum % 10) == 0); 
    }