简体   繁体   中英

Error in calculating sum of even place digits and odd place digits in java

In our directions, we have to get a 16 digit number, then sum all the digits in the odd place from right to left. After that, we have to sum all the even place digits from right to left, double the sum, then take module 9. When I try to run my code, I keep getting "Invalid", even if it is with a valid credit card number.

public static boolean validateCreditCard(long number) {
    double cardSum = 0;
    for (int i = 0; i < 16; i++) {
        long cardnumber = (long) Math.pow(10, i);
        double oddPlaceSum = 0;
        double evenPlaceSum = 0;
        if (i % 2 != 0) {
            oddPlaceSum += ((int)(number % cardnumber / (Math.pow(10, i))));
        } else { // so if i%2 ==0
            evenPlaceSum += ((int)(number % cardnumber / (Math.pow(10, i)) * 2 % 9));
        }
        cardSum += evenPlaceSum + oddPlaceSum;
    }
    if (cardSum % 10 == 0) {
        return true;
        System.out.println("Valid");
    } else {
        return false;
        System.out.println("Invalid");
    }
}

Try this instead :

  • Convert the 16 digit number into a String using Long.toString(number).

  • Iterate through the String character by character and keep track of even and odd indexes.

  • Convert each char to an Integer using Integer.valueOf() thereby adding them incrementally.

  • Voila, you got your evenSum and oddSum. Next steps should be trivial.

     public static boolean validateCreditCard(long number){ String x = Long.toString(number); int evenSum = 0; int oddSum = 0; for(int i=0; i<x.length; i=i+2) { oddSum += Integer.valueOf(s[i]); evenSum += Integer.valueOf(s[i+1]); } //Do the next steps with odd and even sums. 

Also, do handle IndexOutOfBoundsException as appropriate.

You can do it in a single while loop as digits are fixed, like this:

int digit,evensum,oddsum;
int i=16;
while(i > 0){
    digit=number%10;
    if(i%2 == 0)
         evensum+=digit;
    else
         oddsum+=digit;  
    i--;
    digit/=10;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM