summaryrefslogtreecommitdiff
path: root/src/Q3/CreditCard.java
blob: fc4cced324bd3ba5a40d39e0802b931a754f3ed1 (plain)
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
package Q3;

import java.util.*;

public class CreditCard {
  private int evenSum;
  private int oddSum;
  private int sum;
  private String ccNumber;
  private String company;

  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;
    }
  }

  public int getEvenSum() {
    return evenSum;
  }

  public int getOddSum() {
    return oddSum;
  }

  public int getSum() {
    return sum;
  }

  public String getCcNumber() {
    return this.ccNumber;
  }

  public String getCompany() {
    return this.company;
  }

  public boolean isValid() {
    return this.validateCompany() && this.validateLength() && this.validateNumber();
  }

  public boolean isDivisibleBy10() {
    return false;
  }

  public boolean validateCompany() {
    return this.ccNumber.startsWith("4")
        || this.ccNumber.startsWith("5")
        || this.ccNumber.startsWith("37")
        || this.ccNumber.startsWith("6");
  }

  public boolean validateLength() {
    return this.ccNumber.length() >= 13 && this.ccNumber.length() <= 16;
  }

  public boolean validateNumber() {
    for (int i = 0; i < this.ccNumber.length(); i++)
      if (!Character.isDigit(this.ccNumber.charAt(i))) return false;
    return true;
  }

  public boolean validateSums() {
    return false;
  }

  private String identifyCompany(String number) {
    if (validateCompany())
      switch (number.charAt(0)) {
        case '3':
          return "American Express";
        case '4':
          return "Visa";
        case '5':
          return "MasterCard";
        case '6':
          return "Discover";
      }

    return "Unknown";
  }

  private void puts(String format, Object... args) {
    System.out.println(String.format(format, args));
  }
}