I have a function in which I need to set a string to the following format : #####-####-## and padded with leading zeroes.
eg:
1234567 will become 00001-2345-67
98765432109 will become 98765-4321-09
I'm using MaskFormatter and my impression from the documentation was that A represented any letter or digit, and that setPlaceHolderCharacter would pad the string.
I know technically it's for use with text fields but had hoped I could use it in a back-end function, if not is there a different component i should be using?
I have this code below but it throws an exception java.text.ParseException: Invalid character: 1 when it hits mask.valueToString(ndc)
public class NdcFormatter implements MapFunction<Purchase, Purchase> {
private final String maskFormat = "AAAAA-AAAA-AA";
private final Character placeholder = '0';
@Override
public Purchase map(Purchase purchase) throws ParseException {
if(purchase != null){
String ndc = purchase.getNdc();
MaskFormatter mask = new MaskFormatter(maskFormat);
mask.setPlaceholderCharacter(placeholder);
String result = mask.valueToString(ndc);
purchase.setNdc(result);
}
return purchase;
}
}
Here is how to fix ERROR
java.text.ParseException: Invalid character: ...inMaskFormatterSolution the error is in
valueToStringmethod, you have to add this line of code :but you will get a problem like that :
1234567it will return you12345-6700-0000001-2345-67you have to pass00001234567so you have to fix your input value before formatting .
here is the complete code :
to pad the leading zeroes by yourself here is a simple code example.