-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCreditCardValidation.java
136 lines (94 loc) · 2.71 KB
/
CreditCardValidation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import java.util.Scanner;
public class CreditCardValidation {
//final method to determine validity
public static boolean isValid(long number) {
int total = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number);
if ((total % 10 == 0) && (prefixMatched(number, 1) == true) && (getSize(number)>=13 ) && (getSize(number)<=16 )) {
return true;
}
else {
return false;
}
}
//adds double all the even entries
public static int sumOfDoubleEvenPlace(long number) {
int result = 0;
long digits = 0;
while (number > 0) {
digits = number % 100;
result += getDigit((int) (digits / 10) * 2);
number = number / 100;
}
return result;
}
//adds digits together
public static int getDigit(int number){
int sum = 0;
while (number > 0) {
sum = sum + number % 10;
number = number / 10;
}
return sum;
}
//adds all the odd entires
public static int sumOfOddPlace(long number) {
int result = 0;
while (number > 0) {
result += (int) (number % 10);
number = number / 100;
}
return result;
}
//checks valid prefix
public static boolean prefixMatched(long number, int d) {
if ((getPrefix(number, d) == 4)
|| (getPrefix(number, d) == 5)
|| (getPrefix(number, d) == 3)) {
if (getPrefix(number, d) == 3) {
}
else if (getPrefix(number, d) == 5) {
}
else if (getPrefix(number, d) == 3) {
}
return true;
}
else {
return false;
}
}
//gets the size of entry
public static int getSize(long d) {
int count = 0;
while (d > 0) {
d = d / 10;
count++;
}
return count;
}
//determines the prefix
public static long getPrefix(long number, int k) {
if (getSize(number) < k) {
return number;
}
else {
int size = (int) getSize(number);
for (int i = 0; i < (size - k); i++) {
number = number / 10;
}
return number;
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//gets user input
System.out.print("Enter a credit card number as a long integer: ");
long usernum = input.nextLong();
//prints outcome
if (isValid(usernum) == true) {
System.out.println(usernum + " is valid. ");
}
else {
System.out.println(usernum + " is invalid. ");
}
}
}