Verifying the legitimacy of credit card with java code

From , 3 Years ago, written in Java, viewed 102 times.
URL https://pastebin.vip/view/41bacf56
  1. /*
  2.  * 当你输入信用卡号码的时候,有没有担心输错了而造成损失呢?其实可以不必这么担心,
  3.  * 因为并不是一个随便的信用卡号码都是合法的,它必须通过Luhn算法来验证通过。
  4.     该校验的过程:
  5. 1、从卡号最后一位数字开始,逆向将奇数位(1、3、5等等)相加。
  6. 2、从卡号最后一位数字开始,逆向将偶数位数字,先乘以2(如果乘积为两位数,则将其减去9),再求和。
  7. 3、将奇数位总和加上偶数位总和,结果应该可以被10整除。
  8. 例如,卡号是:5432123456788881
  9. 则奇数、偶数位(用红色标出)分布:5432123456788881
  10. 奇数位和=35
  11. 偶数位乘以2(有些要减去9)的结果:1 6 2 6 1 5 7 7,求和=35。
  12. 最后35+35=70 可以被10整除,认定校验通过。
  13.  
  14. 请编写一个程序,从键盘输入卡号,然后判断是否校验通过。通过显示:“成功”,否则显示“失败”。
  15. 比如,用户输入:356827027232780
  16. 程序输出:成功
  17.  */  
  18. import java.util.Scanner;  
  19. public class Demo10 {  
  20.     public static int calc(String s){  
  21.         int odd = 0;  
  22.         int even = 0;  
  23.         int t = 0;  
  24.         char[] c = s.toCharArray();  
  25.         if(c.length%2==0){  // 如果位数为偶数个,则第一个数从偶数开始算起  
  26.             for(int i=0;i<c.length;i++){  
  27.                 t = c[i]-'0';  
  28.                 if(i%2!=0){  
  29.                     odd += t;  
  30.                 }else{       // 第一个数加入到偶数  
  31.                     if(t*2>=10){  
  32.                         even += t*2-9;  
  33.                     }else{  
  34.                         even += t*2;  
  35.                     }  
  36.                 }  
  37.             }  
  38.         }else{       // 如果位数为奇数个,则第一个数从奇数开始算起  
  39.             for(int i=0;i<c.length;i++){  
  40.                 t = c[i]-'0';  
  41.                 if(i%2==0){ // 第一个数加入到奇数  
  42.                     odd += t;  
  43.                 }else{  
  44.                     if(t*2>=10){  
  45.                         even += t*2-9;  
  46.                     }else{  
  47.                         even += t*2;  
  48.                     }  
  49.                 }  
  50.             }  
  51.         }  
  52.         return odd+even;    // 返回奇数位总和加上偶数位总和  
  53.     }  
  54.     public static void main(String[] args){  
  55.         Scanner scan = new Scanner(System.in);  
  56.         System.out.print("输入卡号:");  
  57.         String s = scan.nextLine();  
  58.         if(calc(s)%10==0){  // 结果可以被10整除  
  59.             System.out.println("成功");  
  60.         }else{  
  61.             System.out.println("失败");  
  62.         }  
  63.     }  
  64. }  
  65.  
  66.  
  67. //java/7085

Reply to "Verifying the legitimacy of credit card with java code"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website