Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package jav1_1;
- import java.util.Scanner;
- public class Credit {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- long ccnum;
- do{
- System.out.println("Enter a number");
- ccnum = sc.nextLong();
- }
- while(ccnum<0);
- sc.close();
- //"count" variable to count no. of digits in ccnumber
- int count=0;
- long num=ccnum;
- //this while loop counts no.of digits in ccnumber
- while(num>0)
- {
- num=num/10;
- count++;
- }
- //below if condn checks ccnumber contains how many digits and sees if valid or not
- if(count!=15 && count!=13 && count!=16)
- {
- System.out.println("Invalid credit card");
- }
- else
- {
- //below array stores the ccnum in reverse order =>1 digit each
- int[] number = new int[count];
- for(int i=0;i<count;i++)
- {
- number[i]=(int) (ccnum%10);
- ccnum=ccnum/10;
- }
- //below array stores the same reverse array by eliminating 1st num and makes it '0' kind of empty
- int[] orignumber = new int[count];
- for(int i=1;i<count;i++)
- {
- orignumber[i]=number[i];
- }
- //below process multiplies '2' to the 'number' array elements in index 1,3,5...so on and
- //if any of it is double digit it makes it single als0(while loop)
- int digit =0;
- for(int i=1;i<count;i+=2)
- {
- number[i]*=2;
- while(number[i]>9)
- {
- digit=number[i]%10;
- number[i]=number[i]/10;
- number[i]=number[i]+digit;
- }
- }
- //this is optional to see the 2 arrays how they are for understanding
- /*for(int i=0;i<count;i++)
- {
- System.out.print(number[i]);
- }
- System.out.println();
- for(int i=0;i<count;i++)
- {
- System.out.print(orignumber[i]);
- }
- */
- //this process adds all the digits which are multiplied by 2 and total is called 'sum2nd'
- int sum2nd=0;
- for(int i=1;i<count;i+=2)
- {
- sum2nd=sum2nd+number[i];
- }
- //this process adds 'sum2nd' and the remaining elements which 'not' multiplied by 2
- int checksum=sum2nd;
- for(int i=0;i<count;i+=2)
- {
- checksum=checksum+number[i];
- }
- //this checks if the totalsum(checksum) ends in zero or not
- if(checksum%10==0)
- {
- System.out.println("\nValid card");
- //visa starts with 4
- if((orignumber[count-1]==4))
- {
- System.out.println("Visa card");
- }
- //visa starts with 4
- else if((orignumber[count-2]==7) && (orignumber[count-1]==4||orignumber[count-1]==3))
- {
- System.out.println("Amex card");
- }
- //Amex starts with 34,37
- else if((orignumber[count-1]==5) && (orignumber[count-2]==1||orignumber[count-2]==2||orignumber[count-2]==3||orignumber[count-2]==4||orignumber[count-2]==5))
- {
- System.out.println("Master card");
- }
- //master card starts with 51,52,53,54,55
- else
- {
- System.out.println("Invalid card");
- }
- }
- else
- {
- System.out.println("Invalid");
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment