How do I format my string in GWT?
I made a method
Formatter format = new Formatter();
int matches = 0;
Formatter formattedString = format.format("%d numbers(s, args) in correct position", matches);
return formattedString.toString();
But it complains by saying
Validating newly compiled units
[ERROR] Errors in 'file:/C:/Documents%20and%20Settings/kkshetri/workspace/MasterMind/MasterMind/src/com/kunjan/MasterMind/client/MasterMind.java'
[ERROR] Line 84: No source code is available for type java.util.Formatter; did you forget to inherit a required module?
Isn't Formatter included?
See the official page on GWT date and number formatting.
They suggest the following:
myNum decimal = 33.23232;
myString = NumberFormat.getFormat("#.00").format(decimal);
It is best to use their supported, optimized methods, than to cook up your own non-optimal method. Their compiler will be optimizing them all to nearly the same thing anyway in the end.
A very simple replacement for String.format() in GWT 2.1+:
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.regexp.shared.SplitResult;
public static String format(final String format, final Object... args) {
final RegExp regex = RegExp.compile("%[a-z]");
final SplitResult split = regex.split(format);
final StringBuffer msg = new StringBuffer();
for (int pos = 0; pos < split.length() - 1; ++pos) {
msg.append(split.get(pos));
msg.append(args[pos].toString());
}
msg.append(split.get(split.length() - 1));
return msg.toString();
}
UPDATE: Please see (and vote up) Joseph Lust's post below before looking further at this answer.
Looks like formatter isn't included according to this post. However, they suggest some alternatives.
Or even simpler, not using RegExp, and using only Strings:
public static String format(final String format, final String... args) {
String[] split = format.split("%s");
final StringBuffer msg = new StringBuffer();
for (int pos = 0; pos < split.length - 1; pos += 1) {
msg.append(split[pos]);
msg.append(args[pos]);
}
msg.append(split[split.length - 1]);
return msg.toString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With