-1

Java. One of the rules for my creditcard number is that the sum of the first four digits must be 1 less than the sum of the last four digits, but I think because my number has dashes(-) separating them, it's causing error 5. I need to have the dashes. What should I change in this structure?

    int firstfourdigits = 0;
    int lastfourdigits = 0;
   
    for(int i=0; i<4; i++)
        firstfourdigits = firstfourdigits + Character.getNumericValue(ccNumber.charAt(i));
    for (int i=0, m = ccNumber.length()-1; i<4; i++, m--)
        lastfourdigits = lastfourdigits + Character.getNumericValue(ccNumber.charAt(m));

      
    if(lastfourdigits!= firstfourdigits -1){
        valid = false;
        errorCode = 5;
        return;
    }
  • 1
    You should skip the dashes--either by stripping first, or taking them into account during processing. – Dave Newton Feb 15 '21 at 19:20
  • Keep a reference to the original string, create a string with the dashes removed and perform your logic on that one – RobOhRob Feb 15 '21 at 19:22
  • `String toProcess = cardNumberString.replace("-", "");` – DevilsHnd - 退職した Feb 15 '21 at 20:03
  • 2
    Does this answer your question? [credit card numbers need to be added without the dash](https://stackoverflow.com/questions/66212668/credit-card-numbers-need-to-be-added-without-the-dash) – Yoni Feb 15 '21 at 20:14
  • 1
    You should avoid asking the same question twice. You should update your original question as your previous question was also on ignoring dashes in credit card numbers – Yoni Feb 15 '21 at 20:30
  • 1
    I already closed it as a duplicate. This question should deleted either by the OP or by a moderator. – WJS Feb 15 '21 at 20:32

1 Answers1

0

You can create a separate string that has just the digits:

String digits = ccNumber.replaceAll("[^0-9]", "");

Then do your validation using that string.

Erik
  • 578
  • 2
  • 9
  • I can't because I need the dashes showing. – ionlygeterrors Feb 15 '21 at 19:48
  • You could keep the `ccNumber` string around for display, etc. The `digits` string would be used only for the validation logic. – Erik Feb 15 '21 at 20:14
  • so when I did this: String digits = ccNumber.replace("[ˆ0-9]",""); int firstfourdigits = 0; int lastfourdigits = 0; instead of running for the number 4807-6052-1766 it gave me the error: – ionlygeterrors Feb 15 '21 at 20:22
  • it gave me the error: java.lang.NumberFormatException: For input string: "--" – ionlygeterrors Feb 15 '21 at 20:25
  • Make sure you use `replaceAll` and not `replace` as those methods behave differently. – Erik Feb 15 '21 at 22:35
  • `replaceAll("[^0-9]", "")` will remove anything that isn't a digit. `replace("[^0-9]", "")` will just remove the substring `[^0-9]` from the string. – Erik Feb 15 '21 at 22:37