Commit be9f858
Changed files (1)
src
src/Q3/CreditCard.java
@@ -12,17 +12,7 @@ public class CreditCard {
public CreditCard(String num) {
this.ccNumber = num;
this.company = this.identifyCompany(num);
- String reversed = new StringBuilder(num).reverse().toString();
- for (int i = 0; i < reversed.length(); i++) {
- if (!Character.isDigit(reversed.charAt(i))) break;
-
- int digit = Character.getNumericValue(reversed.charAt(i));
- if ((i + 1) % 2 == 0) {
- String value = String.valueOf(digit * 2);
- for (int j = 0; j < value.length(); j++)
- this.evenSum += Character.getNumericValue(value.charAt(j));
- } else this.oddSum += digit;
- }
+ this.calculateSums(num);
}
public int getEvenSum() {
@@ -46,11 +36,15 @@ public class CreditCard {
}
public boolean isValid() {
- return this.validateCompany() && this.validateLength() && this.validateNumber();
+ return this.validateCompany()
+ && this.validateLength()
+ && this.validateNumber()
+ && this.validateSums()
+ && this.isDivisibleBy10();
}
public boolean isDivisibleBy10() {
- return false;
+ return ((this.evenSum + this.oddSum) % 10) == 0;
}
public boolean validateCompany() {
@@ -71,7 +65,7 @@ public class CreditCard {
}
public boolean validateSums() {
- return false;
+ return this.evenSum > 0 && this.oddSum > 0;
}
private String identifyCompany(String number) {
@@ -90,7 +84,33 @@ public class CreditCard {
return "Unknown";
}
- private void puts(String format, Object... args) {
- System.out.println(String.format(format, args));
+ private void calculateSums(String number) {
+ if (!validateNumber()) return;
+
+ String reversed = this.reverseString(number);
+ for (int i = 0; i < reversed.length(); i++) {
+ int digit = this.digitFrom(reversed, i);
+ if (this.isOdd(i + 1)) this.oddSum += digit;
+ else {
+ String value = String.valueOf(digit * 2);
+ for (int j = 0; j < value.length(); j++) this.evenSum += this.digitFrom(value, j);
+ }
+ }
+ }
+
+ private String reverseString(String value) {
+ return new StringBuilder(value).reverse().toString();
+ }
+
+ private boolean isEven(int number) {
+ return number % 2 == 0;
+ }
+
+ private boolean isOdd(int number) {
+ return !this.isEven(number);
+ }
+
+ private int digitFrom(String input, int index) {
+ return Character.getNumericValue(input.charAt(index));
}
}