• Post Reply Bookmark Topic Watch Topic
  • New Topic

Masking a credit card value  RSS feed

 
Dan Acuff
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code produces a mask that looks like 4xxx-xxxx-xxxx-1221

We want a mask that is simply the last 4 digits.

How would I modify this code to get that result?

public static String maskNumber(String accno) {
StringBuffer sb = new StringBuffer();
if (StringUtils.isNotBlank(accno)) {
int length = accno.length();
int mask = length;
if (length > 7) {
mask = length - 4;

for (int i = 0; i < mask; i++) {
if (i % 4 == 0) {
sb.append("-");
}
sb.append("x");
}
sb.reverse();
sb.append(accno.substring(mask));
sb.replace(0, 1, String.valueOf(accno.charAt(0)));

} else {
// if account.length too short, do not show length and mark
// as xxxxxN
mask = length - 1;

sb.append("xxxxx");
sb.append(accno.substring(mask));
if (length > 4) {
sb.replace(0, 1, String.valueOf(accno.charAt(0)));
}
}
}
return sb.toString();
}
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'll need to specify the problem a bit more clearly. 4 digits only? Or a bunch of xs followed by 4 digits? What can the inputs look like? I have to say parts of this original -- especially the call to reverse() -- are a bit hard to divine the meaning of.
 
Dan Acuff
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ahh yes, 4 digits only.

I think I got it by just reverse engineering the previous coders work.

public static String maskNumber(String accno) {
StringBuffer sb = new StringBuffer();
if (StringUtils.isNotBlank(accno)) {
int length = accno.length();
int mask = length;
if (length > 7) {
mask = length - 4;

sb.append(accno.substring(mask));


} else {
// if account.length too short, do not show length and mark
// as xxxxxN
mask = length - 1;

sb.append("xxxxx");
sb.append(accno.substring(mask));
if (length > 4) {
sb.replace(0, 1, String.valueOf(accno.charAt(0)));
}
}
}
return sb.toString();
}
 
Campbell Ritchie
Marshal
Posts: 55772
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your code is very hard to read if you don't use the Code button.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!